我想用 json 将我的数据保存在数据库中。我正在使用以下代码,它既没有给我任何错误,也没有能够将数据保存在数据库中。请帮我。我是json的新手。
function myfun() {
var name = $('[id$=txt1]').val();
var email = $('[id$=txt2]').val();
var address = $('[id$=txt3]').val();
var salary = $('[id$=txt4]').val();
var data = { name: name, email: email, address: address, salary: salary };
alert(data.val());
$.ajax({
type: "POST",
url: "Default.aspx/save",
// data: "{'name':'" + name + "','email':'" + email + "','address':'" + address + "','salary':'" + salary + "'}",
data: data,
contentType: "application/json;charset=utf-8",
datatype: "json",
async: true,
success: function(data) {
$('[id$=lbl1]').val(data.d)
},
error: function(msg) {
alert("failed: " + msg);
}
});
}
---------------服务器端代码--------
[System.Web.Services.WebMethod]
public String save(String name, String email, String address, Int32 salary)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText="insert tbfirst values(@name, @email, @address, @salary)";
cmd.Parameters.Add("@name",System.Data.SqlDbType.VarChar,50).Value = name;
cmd.Parameters.Add("@email", System.Data.SqlDbType.VarChar,50).Value = email;
cmd.Parameters.Add("@address", System.Data.SqlDbType.VarChar,50).Value = address;
cmd.Parameters.Add("@salary", System.Data.SqlDbType.Int).Value = salary;
cmd.ExecuteNonQuery();
cmd.Dispose();
return "Success";
}