【问题标题】:I can't read a JSON with getJson我无法使用 getJson 读取 JSON
【发布时间】:2011-10-11 08:43:38
【问题描述】:

我知道我的问题已经被回答了很多次,但我仍然不知道如何让一个为我工作。 我现在正在尝试 2 天通过阅读论坛来解决我的问题,但我可能在基本知识方面有一些问题,我无法找到并且我需要你的帮助。

我有一个创建 JSON 的 servlet(至少我是这么认为的),这里是代码

        JSONObject json = new JSONObject();
    for(int i=0; i<20; i++){
        JSONObject jsonItem = new JSONObject();
        jsonItem.put("position", positions[i]);
        json.accumulate("group", jsonItem);
    }

    String output = json.toString();

    response.setContentType("application/json");    
    PrintWriter out = response.getWriter();  
    out.print(output);
    out.flush();

如果我运行 servlet,我会得到以下信息:

{
  "group": [
    {
      "position": 235
    },
    {
      "position": 61
    },
    {
      "position": 248
    },
    {
      "position": 206
    },
    {
      "position": 26
    },
    {
      "position": 329
    },
    {
      "position": 176
    },
    {
      "position": 180
    },
    {
      "position": 218
    },
    {
      "position": 83
    },
    {
      "position": 177
    },
    {
      "position": 142
    },
    {
      "position": 17
    },
    {
      "position": 249
    },
    {
      "position": 310
    },
    {
      "position": 369
    },
    {
      "position": 251
    },
    {
      "position": 256
    },
    {
      "position": 337
    },
    {
      "position": 63
    }
  ]
}

我的 jQuery 如下:

$(document).ready(function(){
  $("#clickMe2").click(function(){
      alert("something2");
    $.getJSON("/RandomNumGen",function(result){
        alert("something3");
      $.each(result, function(i, field){
        $("#myTarget").append(field + " ");
      });
    });
  });
});

也许这不是正确的阅读方式,但它永远不会进入第二个警报“something3”。所以我认为它从不读取 JSON。 我尝试了很多方法来阅读它,但似乎问题在于从不读取 JSON。

我在 tomcat 7.0.22 上运行 servlet,我有 @WebServlet("/RandomNumGen"),我认为这意味着我不需要 web xml 但没有运行,所以我决定创建一个 web.xml 作为好吧。 奇怪的是,当我尝试使用 MIME "text/html" 返回某些内容并使用正常的 get $.get 获取它时,它确实得到了它,并在浏览器上打印了 [Object object]。

显然我以前没有使用过 JSON,而且我可能会错过基础知识,因为我在教程中运行得非常快。

【问题讨论】:

    标签: jquery json getjson servlet-3.0


    【解决方案1】:

    你的 jquery 是错误的。您必须更改您的$.each。试试这个

    $.each(result.group, function(i, field){
         $("#myTarget").append(field.position + " ");
    });
    

    看看这个 http://jsfiddle.net/xV2vx/

    【讨论】:

    • 感谢您的更正以及更多关于向我介绍 jsfiddle.net 的信息!但是我不认为我错误的“每个”是没有正确运行“alert('something3')”的原因......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2019-10-16
    • 2017-05-28
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多