在實(shí)際項(xiàng)目當(dāng)中,我們經(jīng)常會遇到同一個(gè)域名下不同項(xiàng)目之間通過Ajax相互調(diào)用數(shù)據(jù),這樣問題就來了,如何通過Ajax實(shí)現(xiàn)跨域呢?
解決方案
1.Jsonp
Jsonp解決跨域相對簡單,服務(wù)器無需任何配置。具體實(shí)現(xiàn)如下:
$.ajax({ type: 'get', url: 'http://xxx.com', data: {}, dataType: 'jsonp', success: function (data) { }, error: function (data) { mask.close(); toast('請求失敗'); } });
2.CORS
CORS解決方案需要前端和服務(wù)端共同配置才能實(shí)現(xiàn)
前端
$.ajax({ url: 'http://xxx.com', type: 'post', xhrFields:{ withCredentials:true }, data: {}, success: function(res){ }, error: function(){ alert('服務(wù)器發(fā)生錯誤!'); } });
服務(wù)端(在程序入口文件配置)
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');
總結(jié)
以上所述是小編給大家介紹的Ajax實(shí)現(xiàn)跨域訪問最新解決方案,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com