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;
}
}