我在使用 ajax 查询字符串时遇到一些问题,如果页面没有,我可以发送数据,并且 Info.aspx/Save
效果很好。但是当我用查询字符串填充某些内容然后发布相同的数据时,它将返回 http 500 错误。我对 javascript 中的查询字符串一无所知,我在 C# 中使用它作为 id。
var data = '{name: "' + $("input[name$='name']").val() +
'",description: "' + $("input[name$='description']").val() +
'",code: "' + $("input[name$='code']").val() +'"}';
$.ajax({
type: "POST",
url: "Info.aspx/Save",
data: data,
contentType: "application/json",
dataType: "json",
success: function (data) {
var result = data.d
console.log(result)
if (result > 0)
success.show();
else
error.show();
Metronic.scrollTo(error, -200);
},
error: function () {
console.log('err')
}
});
[WebMethod]
public static int Save(string name, string description, string code)
{
ClassInfo classInfo = new ClassInfo();
return ClassInfo.Save(name, code, description, FileInfo.id);
}
我只是在 C# 中使用查询字符串来填充输入。尽管我发送相同的数据,但在 pgae 的地址栏中没有查询字符串的情况下它也可以工作,如果地址栏中有查询字符串,ajax 会返回 http500 错误,并且 Save
WebMethod
不起作用。
最佳答案
data
类型必须是object
,不能是字符串。
var data = {name: $("input[name$='name']").val() ,description:$("input[name$='description']").val(),code:$("input[name$='code']").val()};
删除 contentType 或将其更改为
"application/x-www-form-urlencoded; charset=utf-8"
然后
$.post('/Info.aspx/Save',data ,
function (data) {
});
或者
$.ajax({
url: '/Info.aspx/Save',
data: data
});
服务器端 您的 json 参数名称必须与 c# 参数名称相同。
[WebMethod(true)]
public static string Save(string name, string description, string code)
{
return name+" "+description+" "+code;
}
可用于Web方法
和查询字符串
(两者均适用)
查询字符串参数需要以 JSON 形式传递。
data: JSON.stringify({ "name": "name", "description": "description","code":"code" }),
contentType: "application/json; charset=utf-8"
服务器端
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static String Save(string name, string description, string code)
{
}
关于javascript - 使用 ajax 时,某些问题页面有一个查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25969887/