我正在尝试从jQuery调用ASMX方法,但没有成功。以下是我的代码,我不明白我遗漏了什么。
文件Something.js,
function setQuestion() {
$.ajax({
type: "POST",
data: "{}",
dataType: "json",
url: "http: //localhost/BoATransformation/Survey.asmx/GetSurvey",
contentType: "application/json; charset=utf-8",
success: onSuccess
});
}
function onSuccess(msg) {
$("#questionCxt").append(msg);
}
文件SomethingElse.cs,
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Survey : System.Web.Services.WebService {
public Survey () {
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetSurvey() {
return "Question: Who is Snoopy?";
}
}
发布于 2009-05-18 19:32:43
最突出的一点是,您使用的是UseHttpGet=true
,但在您的jQuery代码中使用的是POST。
这里还有一个我创建的名为ASMX页面的测试页面。
[WebMethod]
public Catalog[] GetCatalog()
{
Catalog[] catalog = new Catalog[1];
Catalog cat = new Catalog();
cat.Author = "Jim";
cat.BookName ="His Book";
catalog.SetValue(cat, 0);
return catalog;
}
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "default.asmx/GetCatalog",
cache: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: handleHtml,
error: ajaxFailed
});
});
function handleHtml(data, status) {
for (var count in data.d) {
alert(data.d[count].Author);
alert(data.d[count].BookName);
}
}
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' +
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
</script>
发布于 2009-05-18 20:11:04
您必须确保将Json指定为响应格式(如果这是您想要的格式),并且由于security features而摆脱了UseHttpGet
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string GetSurvey() {
return "Question: Who is Snoopy?";
}
发布于 2009-05-18 19:33:39
下面是一个对aspx页面方法的jQuery调用示例,但它类似于asmx页面。
$.ajax(
{
type: "POST",
url: "NDQA.aspx/ValidateRoleName",
data: '{"roleName":"' + $('[id$=RoleNameTextBox]').val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: ValidateSuccess,
error: ValidateError
});
https://stackoverflow.com/questions/879362
复制相似问题