我正在尝试将一些javascript变量存储到sql server数据库中。但是当我运行代码时,会显示一条警告,说明内部服务器错误。
window.onload = function ()
{ codeLatLng(); SaveUserLocation(); return false }
/*===========================================================*/
function SaveUserLocation() {
//Jquery ajax call to server side method
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
//Url is the path of our web method (Page name/function name)
url: "FriendHomePage.aspx/SaveFriendLocation",
//Pass paramenters to the server side function
data: "{'LocationName':'" + userLocationName + "', 'UserID':'" + myUserID + "'}",
success: function (response) {
//Success or failure message e.g. Record saved or not saved successfully
if (response.d == true) {
alert("Record saved successfully");
}
else {
alert("Record could't be saved");
}
},
error: function (xhr, textStatus, error) {
//Show error message(if occured)
alert("Error: " + error);
}
});
}
[WebMethod]
public static bool SaveFriendLocation(string LocationName, int UserID)
{
bool status;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["FTSCS"].ConnectionString))
{
string sql = "INSERT INTO tblLocation (LocationName,UserID) VALUES (@LocationName,@UserID)";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@LocationName", LocationName);
cmd.Parameters.AddWithValue("@UserID", UserID);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
Int32 retVal = cmd.ExecuteNonQuery();
if (retVal > 0)
{
status = true;
}
else
{
status = false;
}
return status;
}
}
}
答案 0 :(得分:0)
错误很可能与您没有传递有效的JSON字符串即{ 'property': 'value' }
这一事实有关。
建议您在序列化JSON时使用JSON.stringify(或等效的)
var data = { LocationName: userLocationName, UserID: myUserID };
...
$.ajax({
...
data: JSON.stringify(data)
});
答案 1 :(得分:0)
我相信在这种情况下你应该打开调试模式设置断点并找出真正的问题。如果您无法解决真实问题,可以在此处发帖提问。由于可能的错误,您的问题看起来很模糊: