AJAX跨域有多种方式。在此只说一下JSONP的方式。
例:
var xhrurl = 'http://localhost:8001/Ajax/ticketNotify.ashx?cu=kefu1'; $.ajax({ type : "get", async : false, url :xhrurl, cache : false, dataType : "jsonp", jsonp: "callbackparam", jsonpCallback:"jsonpCallback1", success : function(json){ alert(json[0].name); }, error:function(e){ alert("error"); } });
服务端代码:
1 String callbackFunName = context.Request["callbackparam"]; 2 context.Response.Write(callbackFunName + "([ { "name":"John"}])");
PS:客户端的jsonp参数是用来通过url传参,传递jsonpCallback参数的参数名,比较拗口,通俗点讲:
jsonp: "callbackparam"
jsonpCallback:"jsonpCallback1"
这两个参数最终会拼接在请求的url后面,变成 http://www.xxx.com/ajax/xxx.ashx?callbackparam=jsonCallback1
服务端要获取这个参数值:"jsonCallback1" ,拼接在要输出的JSON数据最前面,不然就算请求成功你也只会看到警告:
Resource interpreted as Script but transferred with MIME type text/plain:
却看不到success定义的函数执行。