跨域 jsonp
Posted 。低调ヽ继续
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了跨域 jsonp相关的知识,希望对你有一定的参考价值。
$.ajax(‘http://192.168.1.107:8080/test/test.do‘;,{
data:{
username:username,
password1:password1
},
dataType:‘jsonp‘,//服务器返回json格式数据
crossDomain: true,
jsonp: ‘callback‘,
type:‘POST‘,//HTTP请求类型
timeout:10000,//超时时间设置为10秒;
success:function(data){
if(data){
alert("登录成功!");
}else{
alert("登录失败!");
}
},
error:function(xhr,type,errorThrown){
console.log(type);
//alert(xhr);
}
});
后台
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin","*");
response.setContentType("text/json; charset=utf-8");
response.setHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS,DELETE");
response.setHeader("Access-Control-Max-Age","3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
String callback=request.getParameter("callback");
if(null==callback){
System.out.println("不是跨域请求");
}else{
System.out.println("是跨域请求");
}
PrintWriter out=response.getWriter();
String userName=request.getParameter("username");
String passWord=request.getParameter("password1");
Map<String,String> map = new HashMap<String,String>();
map.put("result", "true");
String jsonString="{"a":"1"}";
if("123456".equals(userName) && "123456".equals(passWord)){
//out.write(jsonString);
out.println(callback+"("+jsonString+")");
}else{
//out.write(jsonString);
out.println(callback+"("+jsonString+")");
}
out.flush();
out.close();
}
以上是关于跨域 jsonp的主要内容,如果未能解决你的问题,请参考以下文章