[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string getJsonString()
{
Person p = new Person();
p.name = "Alex";
p.address = "UK";
string jsonString;
jsonString = JsonConvert.SerializeObject(p);
return jsonString;
}
}
$("#clickme").on('click', function () {
$.ajax({
type:"GET",
url: "JsonPage.aspx/getJsonString",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
$("#name").text(response.d.name);
$("#address").text(response.d.address);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}
})
})
});
我试图使用jquery ajax类型调用webmethod:“GET”,第一个问题是但是方法中的断点没有击中。在浏览器中我得到错误“请求json解析失败”。请做什么请帮助...
在jQuery中将方法从GET更改为POST
$("#clickme").on('click', function () {
$.ajax({
url: "Default.aspx/getJsonString",
data: "{}",
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (response) {
debugger;
$("#name").text(response.d.name);
$("#address").text(response.d.address);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}
})
})
并将您的Web方法更改为
[ScriptMethod(UseHttpGet = false)]