加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax 跨域请求

发布时间:2020-12-15 21:28:19 所属栏目:百科 来源:网络整理
导读:随笔 - 71 文章 - 0 评论 - 39 Ajax 跨域请求 客户端JS: 1 var xhrurl = 'http://localhost:8001/Ajax/ticketNotify.ashx?cu=kefu1' ; 2 $.ajax({ 3 type : "get" , 4 async : false ,128); line-height:1.5!important"> 5 url :xhrurl,128); line-height:1

Ajax 跨域请求

客户端JS:

 1 var xhrurl = 'http://localhost:8001/Ajax/ticketNotify.ashx?cu=kefu1';
 2 $.ajax({
 3         type : "get", 4         async : false,128); line-height:1.5!important"> 5         url :xhrurl,128); line-height:1.5!important"> 6         cache :  7         dataType : "jsonp",128); line-height:1.5!important"> 8         jsonp: "callbackparam",128); line-height:1.5!important"> 9         jsonpCallback:"jsonpCallback1",128); line-height:1.5!important">10         success : function(json){
11             alert(json[0].name);
12         },128); line-height:1.5!important">13         error:function(e){
14             alert("error");
15         }
16     });

服务端代码:

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定义的函数执行。



顺带一提:
在chrome浏览器里,还可以在服务端设置header信息
context.Response.AddHeader("Access-Control-Allow-Origin","*");
来达到跨域请求的目的,并且不需要设置ajax以下参数
dataType : "jsonp",jsonp: "callbackparam",jsonpCallback:"jsonpCallback1"

以正常ajax请求方式就可以获得数据。


出处:http://www.cnblogs.com/mahatmasmile/archive/2013/03/29/2989505.html

 
        
 
       
!!!转发请注明出处和作者名称。 !!!转发请注明出处和作者名称。 !!!转发请注明出处和作者名称。 重要的事,说三遍。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读