前台页面:
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
后台Servlet:
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "hello");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(jsonObject.toString());
response.getWriter().flush();
但是前台接受值的时候,通过firebug调试发现抛出“SyntaxError: missing ; before statement“,在百度上搜了半天也没有找到一个靠谱的方法,有好多帖子说是URL问题,但是我肯定URL没有问题。后来转而用google,一下就找到问题根源了,嗨... ... 差距啊,还是推荐使用google。
参考网址:
http://stackoverflow.com/questions/20658674/syntaxerror-missing-before-statement-jquery-jsonp
解决方法:
将 dataType:"jsonp" 这个属性去掉就可以啦,具体原因还没有查,下班了,明日继续刨根问底。
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}});