Jquery异步提交返回json结果问题

来源:互联网 发布:淘宝卖家手机打印快递 编辑:程序博客网 时间:2024/05/01 13:06

问题:  今天做了一个前台通过按钮异步提交到后台获取json串的例子并在前台的回调函数中接受对应的值。但是死命不行,纠结了好久

下面是我的例子:

html部分:

<span style="font-size:18px;"><script type="text/javascript">function jqjson(){$.post('abcJq',{status:0},function(result){alert(result.json1);location.reload();},'json');}</script><input type="button" onclick="jqjson();" value="jq"></span>

servlet部分:

<span style="font-size:18px;">public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();String status = request.getParameter("status");out.print("{'json1':'状态'}");//out.print("{json:'状态'}");out.flush();out.close();}</span>

在servlet中不管是用上面注释的和不注释返回的结果都不能进入到回调函数,我就纳闷了!


于是我就想这用Gson来封装下返回json串看可以不:

修改后的servlet

<span style="font-size:18px;">public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();String status = request.getParameter("status");Gson gson = new Gson(); //这个Gson对象在Gsonjar包中要自己额外导入HashMap<String,String> map = new HashMap<String,String>(); map.put("json1", "状态是0"); String json = gson.toJson(map);out.print(json);out.flush();out.close();}</span>

让人意外的是这个静然就可以成功的调用回调函数;返回正确的值。


于是我就调试发现用Gson返回的json串的格式是{"json1":"状态是0"}

我就很纳闷了这个和我自己写的{'json1':'状态是0'}有什么差别,这里用的是单引号,因为out.print("{'json1':'状态'}");

为的是外面已经用了双引号了,所以才用单引号。

难道是这个问题,于是我就改写了写法servlet如下:

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();String status = request.getParameter("status");out.print("{\"json\":\"状态\"}");out.flush();out.close();}
奇迹般的就可以了,太搞了。