前台页面代码:
<script type="text/javascript">
$(function(){
$.ajax({
type:"get",
async:false,
url:"http://localhost:8080/0hiCN/php-login/getAllNews?callback=?",
dataType:'jsonp',
processData: false,
success:function(data){
alert(data.result);
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}});
});
</script>
后台代码(SpringMVC):
@RequestMapping(value="/getData",method = RequestMethod.GET)
@ResponseBody
public void getAllNews(HttpServletRequest request,HttpServletResponse response) throws IOException{
try {
response.setContentType("text/plain");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
try {
json.put("result", true);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonpCallback = request.getParameter("callback");//客户端请求参数
out.println(jsonpCallback+"("+json.toString()+")");//返回jsonp格式数据
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}