/*当前网址是localhost:3000*/
js代码
$.ajax({
type:”get”,
url:”http://localhost:3000/showAll”,/*url写异域的请求地址*/
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)+”)”);
}
});
}