Ajax實現跨域訪問最新方式

在實際項目當中,咱們常常會遇到同一個域名下不一樣項目之間經過Ajax相互調用數據,這樣問題就來了,如何經過Ajax實現跨域呢?javascript

解決方案

1.Jsonpphp

Jsonp解決跨域相對簡單,服務器無需任何配置。具體實現以下:前端

$.ajax({
    type: 'get',
    url: 'http://xxx.com',
    data: {},
    dataType: 'jsonp',
    success: function (data) {
        
    },
    error: function (data) {
        mask.close();
        toast('請求失敗');
    }
});

2.CORSjava

CORS解決方案須要前端和服務端共同配置才能實現ajax

  • 前端
$.ajax({
    url: 'http://xxx.com',
    type: 'post',
    xhrFields:{
        withCredentials:true
    },
    data: {},
    success: function(res){

    },
    error: function(){
        alert('服務器發生錯誤!');
    }
});
  • 服務端(在程序入口文件配置)
header('Access-Control-Allow-Origin: http://xxx.com');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
相關文章
相關標籤/搜索