如何解决 Ajax 跨域请求不到的问题?

2025-05-10 05:42:29
推荐回答(2个)
回答1:

跨域访问报错:

XMLHttpRequest cannot load http://v.xxx.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. test.html:1  

Resource interpreted as Script but transferred with MIME type text/html:  


以下是3种方式解决ajax跨域问题:

$(function($){  
      var url = '

      $.ajax(url, {  
        data: {  
          'cityname': '襄阳',  
          'dtype': 'jsonp',  
          'key': 'xxxx',  
          '_': new Date().getTime()  
        },  
        dataType: 'jsonp',  
        crossDomain: true,  
        success: function(data) {  
          if(data && data.resultcode == '200'){  
            console.log(data.result.today);  
          }  
        }  
      });  
  
      var url2 = '

      $.getJSON(url2, {  
        'cityname': '北京',  
        'dtype': 'jsonp',  
        'key': 'xxxx',  
        '_': new Date().getTime()  
      }, function(data){  
        if(data && data.resultcode == '200'){  
          console.log(data.result.today);  
        }  
      });  
  
      var url3 = '

      $.get(url3, {  
        'cityname': '澳门',  
        'dtype': 'jsonp',  
        'key': 'xxxx',  
        '_': new Date().getTime()  
      }, function(data){  
        if(data && data.resultcode == '200'){  
          console.log(data.result.today);  
        }  
      }, 'json');  
    });

更多参考我的blog:http://qiaolevip.iteye.com/blog/2117326

回答2:

jsonp 是写 script 标签,只能满足 get 请求。跨域 post 的话,IE8 及以上和其他主流浏览器可以用 window.postMessage 来实现,也就是传说中的 HTML5 方法了,可以看下标准,代码很简单。IE6、7 就用老式的方法,隐藏的 form,target 指向一个隐...