单击插入到ms SQL数据库

onclick insert in to ms sql database

本文关键字:SQL 数据库 ms 插入 单击      更新时间:2023-09-26

我有asp.net应用程序与JavaScript,我想保存在ms sql DB附加信息(时间戳)当一个按钮被点击。

onclick= "functionName();"

函数"functionName()"有另一个任务,我想要另一个函数来存储时间戳

JS写入如下:

function functionName() {
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    }
    var now = new Date(); // You can also any kind of data using query string
    xmlhttp.open("GET", "saveTimespan.aspx?datetime=" + now, true);
    xmlhttp.send();
}

将下面的代码写入saveTimespan.aspx' page as below(remove all markup other than Page(本页目录)后面的代码:

protected void Page_Load(object sender, EventArgs e)
{
    UpdateTimeStamp();
}
public void UpdateTimeStamp()
{
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "UPDATE TargetTable SET DateTimColumnName = @DateTimColumnName";
    cmd.Parameters.AddWithValue("@DateTimColumnName", MyDateTime);
    cmd.CommandType = CommandType.Text;
    try
    {
        using (SqlConnection connection = new SqlConnection("YourConnectionString"))
        {
            cmd.Connection = connection;
            connection.Open();
            cmd.ExecuteNonQuery();
            Response.Write("Data Updated Successfully!");
        }
    }
    catch (Exception ex)
    {
        //Handle exception
    }
}

尝试使用jQuery ajax,会更容易像

<>之前函数functionName() {. ajax({美元url:"test.html",背景:document.body,成功:函数(){(美元).addClass("完成");}});}之前

裁判:http://api.jquery.com/jQuery.ajax/