跨域 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();
}

相关推荐