html5通过jquery实现跨域请求

来源:互联网 发布:大数据调研提纲 编辑:程序博客网 时间:2024/06/16 15:27

jquery中的js实现跨域请求(此处用的是jquery-3.1.1.js)和jdk8

方式一:jsonp实现跨域请求,

function test(){

$.ajax({
url:"http://localhost:9000/hello",
dataType:"jsonp",  
type:"get",
//dataType:"json",
jsonp: "jsonpCallback", 
success:function(result){
debugger;
var msg="";
for(var i=0;i<result.length;i++){
msg=msg+result[i].name+"------"+result[i].show+"-----";
}
}

});
}

java后台返回的数据

String callback = req.getParameter("jsonpCallback");//jsonpCallback为前台jsonp后的参数字符串
return callback + "(" + returnstr+")";//returnstr 为实际返回的字符串,整个串为返回的结果,返回的是一个json数组型的字符串


方式二:
function test2(){
$.ajax({
url:"http://localhost:9000/hello",
dataType:"json",
type:"post",
//herder:"Access-Control-Allow-Origin",
success:function(result){
debugger;
var msg="";
for(var i=0;i<result.length;i++){
msg=msg+result[i].name+"------"+result[i].show+"-----";
}
}

});
}

java后台需要设置:
response.setHeader("Access-Control-Allow-Origin", "*");//*表示允许所有的域的请求,可以写http://www.baidu.com就表示只允许此域的请求,可以写多个域,下面两个应该是设置其他限制,没仔细研究
//response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
//response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept,X-Requested-With");