此代码在mvc2中运行良好,但回到传统的ASPX(因为Sharepoint 2010)。我遇到了错误。谁能告诉我这个框架我做错了什么?
此ajax调用位于$ .ready
中$.ajax({
type: "POST",
dataType: "json",
data: 'siteName=a&siteUrl=b',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
背后的代码
[WebMethod]
public static string DoesNameUrlExist(string siteName, string siteUrl)
{
//do something
return someString;
}
我每次都会收到错误。
答案 0 :(得分:1)
您需要将JSON发送到服务,并通过contentType
标题指示您正在执行此操作:
$.ajax({
type: "POST",
contentType: 'application/json',
data: '{"siteName":"a","siteUrl":"b"}',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
此处有更多信息:http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
此外,如果您使用的是jQuery 1.4,则可以删除dataType
。 jQuery will infer JSON automatically based on the response's Content-Type header
答案 1 :(得分:0)
contentType
声明为json并且响应内容类型不是json,那么jQuery中的Ajax调用总是会给你一个错误。如果您的WebMethod的响应有所不同(例如html或文本),您将始终收到该错误。您可以在方法上设置该响应类型,如下所示:
[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string DoesNameUrlExist(string siteName, string siteUrl)
在WebMethods之外,这也可以这样实现:
Response.ContentType = "application/json";