我试图通过jquery ajax传递数据,但面临问题。我正在以json格式获取数据
像这样数据:' {用户:' + JSON.stringify(user)+'}'
user = {Tdcno: "tw5", Revision: "0", Revision_Date: "22/11/2017", P_Group: "Chain Link", Prod_Desc: "GI wire for chain link", …}
但在此步骤处理之后,它会直接失败。任何帮助都会对解析表示赞赏。
<script type="text/javascript">
$(function () {
$(document).on("click", "[id*=btnFrmSubmit]", function () {
alert("hi");
var user = {};
user.Tdcno = $("[id*=Tdc_No]").val();
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
c#code
[WebMethod]
[ScriptMethod]
public void SaveFrmDetails(User user)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO TDC_PRODUCT1 VALUES(@Tdc_No, @Revision,@Revision_Date,@P_Group,@Prod_Desc,@N_I_Prd_Std,@Appln,@Frm_Supp,@Created_Date,@Created_By)"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
答案 0 :(得分:0)
永远不要手动创建json字符串。与使用JSON.stringify序列化它相比,它更容易出错并且工作量更大。
'{user: ' + JSON.stringify(user) + '}'
生成无效的json,因为未正确引用属性user
对整个数据对象进行字符串化
data: JSON.stringify({user:user}})