ajax跨域请求:
服务端
@RequestMapping("/baseList")
public void baseList(String siteid, String title, Page page,String jsoncallback, HttpServletResponse response){
Map map = new HashMap();
String sql ="1=1";
if(StringUtil.notNullOrEmpty(siteid) && !sql_inj.sql_inj(siteid)){
sql = sql + " and site_id in ("+siteid+")";
}
if(StringUtil.notNullOrEmpty(title) && !sql_inj.sql_inj(title)){
sql = sql + " and INSTR(title,'"+title+"')";
}
map.put("page", page);
map.put("whereclause", sql);
List list = base3Service.selectByHDPage(map);
JSONObject obj = new JSONObject();
obj.put("data", list);
String result ="";
if(StringUtil.isNullOrEmpty(jsoncallback)){
result = obj.toString();
}else{
result = jsoncallback+"("+obj.toString()+")";
}
PrintWriter out = null;
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
try {
out = response.getWriter();
} catch (IOException e1) {
e1.printStackTrace();
}
out.print(result);
}
客户端
Hello World!
list();
function list(){
$.ajax({
async: false,
url: "http://www.liuweilianhe.com/zixuncaiji/base3/baseList.html",
type: "POST",
dataType: 'jsonp',
//jsonp的值自定义,如果使用jsoncallback,那么服务器端,要返回一个jsoncallback的值对应的对象.
jsonp: 'jsoncallback',
//要传递的参数,没有传参时,也一定要写上
data: {
"siteid":"",
"title":"Technology"
},
timeout: 5000,
//返回Json类型
contentType: "application/json;utf-8",
//服务器段返回的对象包含name,data属性.
success: function (result) {
$.each(result.data,function(i,item){
$("#test").append(item.docno+"."+item.siteId+":"+item.title+"("+item.saveTime.time+")
");
})
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}
最后出来的结果
这样我们就实现了ajax跨域请求
领取专属 10元无门槛券
私享最新 技术干货