【问题标题】:Send AJAX request to .aspx page and return JSON向 .aspx 页面发送 AJAX 请求并返回 JSON
【发布时间】:2013-01-15 09:49:36
【问题描述】:
我知道可以向.asmx 页面发送 AJAX 请求。而且我还知道.asmx 页面通过Web 方法处理AJAX 请求。
是否也可以向.aspx 页面发送 AJAX 请求?如果是这样,.aspx 页面是否也通过 Web 方法处理 AJAX 请求?请注意,我想从 .aspx 页面返回 JSON 响应。这可能吗?
【问题讨论】:
标签:
asp.net
json
ajax
web-services
webforms
【解决方案1】:
您可以在 .aspx 页面的代码隐藏中定义 Web 方法,然后调用它们:
[WebMethod]
public static string doSomething(int id)
{
...
return "hello";
}
然后,在您的 jQuery 代码中调用 Web 方法:
$.ajax({
type: "POST",
url: "YourPage.aspx/doSomething",
data: "{'id':'1'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var returnedstring = data.d;
var jsondata = $.parseJSON(data.d);//if you want your data in json
}
});
Here 是一个很好的入门链接。
【解决方案2】:
$.ajax({
url: "(aspx page name/method to be called from the aspx.cs page)",
type: "POST",
dataType: "json",
data: $.toJSON(jsonData),
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
//TO DO after success
}
});
试试上面的代码
【解决方案3】:
如果我正确理解了问题,则 Aspx 与 HTML 相同。它将呈现为 HTML。但唯一的区别是服务器端和控件通过状态机制保留状态。
所以你可以做 jquery $.ajax() 函数。
$.ajax({
url: UrlToGetData,
dataType:'json',
success:function(data){
//do some thing with data.
}
});
或者如果你想在响应中写出json值,那么使用Response.ContentType
首先使用任何 Javascript 序列化程序(JSON.NET),然后像这样设置 contentType。
Response.ContentType="application/json";