原文来自 — 跨域Ajax要领 – Eson小博客 uninote
典范Ajax
示例:
-
XMLHttpRequest
原生体式格局
var request = new XMLHttpRequest();
request.open("POST", "index.php");
var data = "parameter1" + encodeURIComponent(parameter_one) + "¶meter2" + encodeURIComponent(parameter_two);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function() {
if (request.readyState===4) {
if (request.status===200) {
var ret = request.responseText;
//做有意义的事
} else {
alert("发作毛病:" + request.status);
}
}
}
jQuery
$.ajax({
type:"POST",
url:'index.php',
dataType:"json",
data:{
"parameter1":parameter_one,
"parameter2":parameter_two
},
success:function(ret){
//做有意义的事
},
error:function(jqXHR){
if (jqXHR.status!=200) {
alert("发作毛病:" + jqXHR.status);
}
}
});
跨域Ajax
计划:
计划A:JSONP
- 前端要求页面:
$.ajax({
type:"POST",
url:'http://127.0.0.1/test/Ajax_jsonp/service.php',
dataType:"jsonp",
jsonp:"jsonp",
data:{
"parameter1":parameter_one,
"parameter2":parameter_two
},
success:function(ret){
//做有意义的事
alert(JSON.stringify(ret));
console.log(ret);
},
error:function(jqXHR){
if (jqXHR.status!=200) {
alert("发作毛病:" + jqXHR.status);
}
}
});
- 后端相应页面:
注重后端相应是GET
<?php
if (!empty($_GET['jsonp'])) {
$jsonp = $_GET['jsonp'];
$ret = json_encode($_GET);
echo "{$jsonp}({$ret})";
}
计划B:XHR2
服务端增加相应头信息(IE10以下不支持)
header("Access-Control-Allow-Origin:*");//许可一切泉源接见
header("Access-Control-Allow-Method:POST,GET");//许可接见的体式格局
最终计划:后端代办
curl