如何在ASP.Net网站上为getJson调用支持JSONP返回?
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');
}
});
上一个函数既不会触发成功也不会触发错误函数
答案 0 :(得分:2)
在服务器上,您可以编写一个返回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');
}
});