在服务器上,您可以编写一个返回 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
查询字符串参数,如果指定,它将把 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');
}
});