【问题标题】:json not received in jsp through jquery-ajax [duplicate]通过jquery-ajax在jsp中未收到json [重复]
【发布时间】:2012-05-23 03:56:06
【问题描述】:

我通过 ajax 从 jsp 向 servlet 发送 2 个数据,servlet 只是获取这些数据,然后转换为 json obj 并返回该 json。现在 jsp 得到那个 json 来显示这两个数据。 ajax 正在成功执行 servlet,但每次都提醒我错误而不是成功。请告诉我应该怎么做才能在警报中显示这些数据? details.jsp:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>            
    function doajax(){
        $.ajax({
            url: "AccountDetails",
            type: "post",
            dataType: "json",
            data: { "mobileNo":"01914752849", "fullName":"Md. Muzahid-ul Islam" },
            error:function(){
                alert("error occured!!!");
            },
            success:function(data){
                alert(data.fullName + "\n" + data.mobileNo);
            }
         });
      }
</script>

AccountDetails.java(servlet):

PrintWriter out = response.getWriter();
try {
    String fullName = request.getParameter("fullName");
    String mobileNo = request.getParameter("mobileNo");
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("fullName", fullName);
    jsonObject.put("mobileNo", mobileNo);
    out.println(jsonObject);
} finally {
    out.flush();
    out.close();
}

【问题讨论】:

  • 您是否在 firebug 中遇到错误?
  • *首先尝试将jsp中的内容类型设置为application/json,然后检查您是否为url AccountDetails配置了web.xml然后做这个伎俩,我认为它会解决问题
  • 感谢您的回复。 @jayantha,不幸的是我不熟悉萤火虫:(@ankur20us,检查脚本代码,我在那里指定内容类型。此外,我正在使用这两行 b4 创建“输出”obj:response.setContentType("application/json"); response.setCharacterEncoding("UTF-8");跨度>
  • 啊.. 你能用 Chrome 看看控制台吗
  • &lt;form method="post"&gt; &lt;input class="fr submit" id="btnUpdateTop" name="btnUpdateTop" type="submit" value="Update" onclick="doajax()" /&gt; &lt;/form&gt; 这是我调用脚本的 html 部分。有趣的部分是当我在跨步阶段调试@chrome 时,它​​向我展示了数据。但是当没有调试时它什么都没有显示(在评论错误部分之后):(我对有这样的问题感到困惑!!!

标签: jquery ajax json jsp servlets


【解决方案1】:

将 servlet 中的代码编辑为

Gson gson = new Gson();
JsonElement element = gson.toJsonTree(<Object_to_be_passed or model_class>);
out.write(element.toString());

你还必须在servlet中导入两个包com.google.gson.Gsoncom.google.gson.JsonElement

注意:尝试通过将数据包装在模型类中来转发数据

希望对你有帮助..:)

【讨论】:

    猜你喜欢
    • 2016-01-09
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    相关资源
    最近更新 更多