JSONP
jsonp: function(url, callbackFunc, data) //跨域請求
{
var data = arguments[2] ? arguments[2] : {};
if(url != '' && callbackFunc != '') {
$.ajax({
type: 'get',
dataType: 'jsonp',
url: url,
jsonp: "callback",
jsonpCallback: callbackFunc,
data: data,
async: true,
success: function(data) {
console.log('跨域請求成功');
},
error: function() {
console.log('跨域請求失敗');
}
});
} else
alert('URL,回調函數不能爲空');
}
function callbackFunc(res)
{
}
echo 'callbackFunc({age:18})';
CORS跨域
前端請求按照正常的AJAX請求即可
目前自己隨手測過的可以使用的瀏覽器有:360,IE8+,chrome
Hybrid APP跨域
request: function(url, data, callback, type) {
xhr = new plus.net.XMLHttpRequest();
type = arguments[3] ? arguments[3] : 'GET';
data = arguments[1] ? arguments[1] : '';
xhr.onreadystatechange = function() {
switch(xhr.readyState) {
case 4:
if(xhr.status == 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert("xhr請求失敗:" + xhr.readyState);
}
break;
}
}
switch(type.toUpperCase()) {
case 'GET':
xhr.open(type, url + '?' + data);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send();
break;
case 'POST':
xhr.open(type, url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(data);
break;
}
}