[英]Send AJAX request to .aspx page and return JSON
I know that it is possible to send an AJAX request to an .asmx
page. 我知道可以向.asmx
页面发送AJAX请求。 And I also know that an .asmx
page handles an AJAX request via a web method. 我还知道.asmx
页面通过Web方法处理AJAX请求。
Is it also possible to send an AJAX request to an .aspx
page? 是否也可以向.aspx
页面发送AJAX请求? If so, does an .aspx
page also handle an AJAX request via a web method? 如果是这样, .aspx
页面是否也通过Web方法处理AJAX请求? Note that I would like to return a JSON response from the .aspx
page. 请注意,我想从.aspx
页面返回JSON响应。 Is this possible? 这可能吗?
You can define web methods in the code-behind of your .aspx
page and then call them: 您可以在.aspx
页面的代码隐藏中定义Web方法,然后调用它们:
[WebMethod]
public static string doSomething(int id)
{
...
return "hello";
}
And then, to call a web method in your jQuery code: 然后,在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
}
});
if i understood question correctly, Aspx is same as HTML. 如果我正确理解问题,Aspx与HTML相同。 It will be rendered as HTML. 它将呈现为HTML。 but only difference is Server Side and Controls retaining the states with state mechanism. 但唯一的区别是服务器端和控件保留状态机制的状态。
so you can do jquery $.ajax()
function. 所以你可以做jquery $.ajax()
函数。
$.ajax({
url: UrlToGetData,
dataType:'json',
success:function(data){
//do some thing with data.
}
});
or if you want to write out json value to the response, then use Response.ContentType
first use any Javascript serializer(JSON.NET) , then set the contentType like this. 或者如果要将json值写入响应,则使用Response.ContentType
首先使用任何Javascript序列化程序(JSON.NET),然后像这样设置contentType。
Response.ContentType="application/json";
$.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
}
});
Try the above code 试试上面的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.