Jquery 在ASP.NET中支持JSONP返回
如何在ASP.Net网站中为getJson调用支持JSONP返回Jquery 在ASP.NET中支持JSONP返回,jquery,jsonp,getjson,Jquery,Jsonp,Getjson,如何在ASP.Net网站中为getJson调用支持JSONP返回 var url = "http://demo.dreamacc.com/TextTable.json?callback=?"; $.ajax({ type: 'GET', url: url, async: false, jsonpCallback: 'jsonCallback', contentT
var url = "http://demo.dreamacc.com/TextTable.json?callback=?";
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (ooo) {
alert('hi');
alert(ooo);
},
error: function () {
alert('w');
}
});
前面的函数不会在服务器上启动success或error函数,您可以编写一个处理程序,返回JSONP响应:
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// set the response content type to application/json
context.Response.ContentType = "application/json";
// generate some JSON that we would like to return to the client
string json = new JavaScriptSerializer().Serialize(new
{
status = "success"
});
// get the callback query string parameter
var callback = context.Request["callback"];
if (!string.IsNullOrEmpty(callback))
{
// if the callback parameter is present wrap the JSON
// into this parameter => convert to JSONP
json = string.Format("{0}({1})", callback, json);
}
// write the JSON/JSONP to the response
context.Response.Write(json);
}
public bool IsReusable
{
get { return true; }
}
}
这里的想法是,通用处理程序将检查是否存在callback
querystring参数,如果指定,它将把JSON包装到这个回调中
现在,您可以将$.ajax调用指向此服务器端处理程序:
var url = "http://demo.dreamacc.com/MyHandler";
$.ajax({
type: 'GET',
url: url,
jsonp: 'callback',
dataType: 'jsonp',
contentType: "application/json",
dataType: 'jsonp',
success: function (result) {
alert(result.success);
},
error: function () {
alert('error');
}
});
这个url正确吗?var url=“”;我的答案中的url现在指向需要在服务器上编写的通用处理程序,以便支持JSONP。如果服务器不支持JSONP,则不能通过客户端调用使用它。因此,您需要做的第一件事是在服务器上添加对JSONP的支持。如果域不同,请记住在调用中添加
CORS
support($.support.CORS=true;
)。我添加了处理程序,当指向它或指向需要读取的文件时,我没有收到响应,既没有成功也没有失败。@balexandre,JSONP的全部要点是您不需要COR。