我已经阅读了同一问题的其他回复,但未能解决这个问题。我正在尝试将JSON字符串发布到我的服务器(.NET),解析它并存储一些值 - 代码如下。一切正常(即数据最终在我的数据库中,但它仍然会引发500错误)。用Fiddler等调查了它但没有成功
我的代码中可能存在很多其他问题 - 目前只是一些实验,但是会感激任何建议......
首先,jQuery帖子:
function PostData(value) {
$.ajax({
type: "POST",
url: "Default.aspx/PostData",
data: JSON.stringify({ postedData: value }),
contentType: "application/json",
dataType: "json",
success: function (msg) {
console.log("success: " + msg.d);
},
error: function (xhr, textStatus, error) {
console.log("error:" + xhr.statusText + " " + textStatus + " " + error);
}
});
}
接下来,服务器端齿轮:
[WebMethod]
public static string PostData(string postedData)
{
_PostData(postedData);
return null;
}
public static void _PostData(string postedData)
{
JObject o = JObject.Parse(postedData);
string id = (string)o.SelectToken("id");
using (SqlConnection sql = new SqlConnection(connectionString))
using (SqlCommand cmd = sql.CreateCommand())
{
try
{
cmd.CommandText = "INSERT into Table1 (userId, data) VALUES (@userIdValue, @dataValue)";
cmd.Parameters.AddWithValue("@userIdValue", id);
cmd.Parameters.AddWithValue("@dataValue", postedData);
sql.Open();
cmd.Connection = sql;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}