根據同源策略,ajax不能請求域值和端口號不同的url,則有以下三種處理方式。
1.H5中的XHR2已經默認支持跨域訪問,只需要在服務端入口文件加上響應頭header("Access-Control-Allow-Origin:*");
2.使用jsonp方式取代xhr方式,在客戶端設置,在服務端設置。如下。
js代碼
$.ajax({
type:
"get"
,
dataType:
"jsonp"
,
/*加上datatype*/
jsonpCallback:
"cb"
,
/*設置一個回調函數,名字隨便取,和下面的函數裏的名字相同就行*/
success:
function
(){
。。。
}
});
/*而在異域服務器上,*/
app.js
app.get(
'/showAll'
,students.showAll);
/*這和不跨域的寫法相同*/
/*在異域服務器的showAll函數裏,*/
var
db = require(
"./database"
);
exports.showAll
=
function
(req,res){
/**設置響應頭允許ajax跨域訪問**/
res.setHeader(
"Access-Control-Allow-Origin"
,
"*"
);
/*星號表示所有的異域請求都可以接受,*/
res.setHeader(
"Access-Control-Allow-Methods"
,
"GET,POST"
);
var
con = db.getCon();
con.query(
"select
* from t_students"
,
function
(error,rows){
if
(error){
console.log(
"數據庫出錯:"
+error);
}
else
{
/*注意這裏,返回的就是jsonP的回調函數名+數據了*/
res.send(
"cb("
+JSON.stringify(r)+
")"
);
}
});
}
$.getJSON(
"http://e.hnce.com.cn/tools/ajax.aspx?jsoncallback=?"
,
{ id: 0, action:
'jobcategoryjson'
},
function
(json)
{ alert(json[0].pid); alert(json[0].items[0]._name); });