ajax jsonp 跨域
js写法:
$.ajax({
url : url,
dataType:"jsonp",
data:data,
jsonp:'jsonpCallback',
type: "GET",
success:function(result){
if(result.success){
//刷新当前页面
window.location.reload();
}else{
alert(result.message);
}
},
error:function(result){
console.log(result);
}
});
controller中写法:
@RequestMapping(value = "getjsonp",method = { RequestMethod.GET })
public void getjsonp(HttpServletRequest request,HttpServletResponse response,) throws IOException {
HttpJsonResult<String> result = new HttpJsonResult<String>();
result.setMessage("123");
}
PrintWriter out = response.getWriter();
JSONObject resultJSON = JSONObject.fromObject(result); //根据需要拼装json
String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数
out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式数据
out.flush();
out.close();
}
封装类:
public class HttpJsonResult<T> implements Serializable { public HttpJsonResult() { } public HttpJsonResult(T data) { this.data = data; } public HttpJsonResult(String errorMessage) { this.success = false; this.message = errorMessage; } private Boolean success = true; public Boolean getSuccess() { return this.success; } private T data; public T getData() { return data; } public void setData(T data) { this.data = data; } private String message; public String getMessage() { return this.message; } public void setMessage(String message) { this.success = false; this.message = message; } private Integer totalCount = 0; public void setTotalCount(Integer count) { this.totalCount = count; } public Integer getTotalCount() { return this.totalCount; } }
原文链接:https://www.f2er.com/ajax/162325.html