跨域ajax提交数据

来源:互联网 发布:kettle java jndi 编辑:程序博客网 时间:2024/06/05 11:27
//不需要返回数据
$.ajax({
  type : "GET", 
  url: 'http://www.xxx.com/savePhone',
  contentType: "application/x-www-form-urlencoded",
  dataType: 'JSONP',
  data: {userName:username,phone:phone,industry:"m.tradingwin.com"},
  success : function(result) {
         
  }
});




//需要返回数据
$.ajax({  
type : "GET",  
async : false,  
url : "http://www.xxx.com/savePhone,  
dataType : "jsonp",  
jsonp : "callback", //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)  
jsonpCallback : "handler", //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据  
success : function(json) {  
alert( json);  //返回的信息
},  
error : function() {  
alert('fail');  
       }  
 });  






假如是post请求,需要在服务端加上


@RequestMapping(value = "/savePhone", method = RequestMethod.POST))
String void method(@PathVariable String jsoncallback){  
     // 如果为自定义,这里callback=handler,如果为jQuery默认,则为随机jsonp1356493334400之类的数据  
response.setHeader("Access-Control-Allow-Origin", "*");
}  


传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名
@RequestMapping(value = "/savePhone", method = RequestMethod.GET))
String void method(@PathVariable String jsoncallback){  
     // 如果为自定义,这里callback=handler,如果为jQuery默认,则为随机jsonp1356493334400之类的数据  
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();  
out.print(jsoncallback + "('"+str+"')");// string 可以为json数据 
out.flush();  
out.close();
}  










原创粉丝点击