尝试在 aspx 页面上调用 Web 方法时获取 aspx 页面 html。这是 jQuery 代码
$(function () {
$.ajax({
type: 'POST',
url: 'Default.aspx/Hello',
data: "{}",
async: false,
success: function (response) {
console.log('Success: ', response);
},
error: function (error) {
console.log('Error: ', error);
}
});
});
这是网络方法代码
[System.Web.Services.WebMethod]
public static string Hello()
{
string returnString = "hoiiiiiii";
return returnString;
}
任何人都可以指出什么可能是错误的吗?
最佳答案
有两件事:
- 您的 jQuery
.ajax()
函数中缺少contentType
。 您需要考虑 JSON 响应中的
.d
值。$.ajax({ type: "POST", url: "Default.aspx/Hello", data: "{}", async: false, contentType: "application/json; charset=utf-8", dataType: "json", success: function(result) { if (result.hasOwnProperty("d")) { // The .d is part of the result so reference it // to get to the actual JSON data of interest console.log('Success: ', result.d); } else { // No .d; so just use result console.log('Success: ', result); } } });
Note: The
.d
syntax was an anti-XSS protection put in by Microsoft in the ASP.NET 3.5 release of ASP.NET AJAX; therefore the check to see if the.d
property is there or not.
关于c# - 无法使用 jquery ajax 调用 aspx 页面 Web 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20658042/