无法使用jQuery检索json数据

时间:2011-01-29 13:36:01

标签: java jquery json

我正在尝试从servlet中检索JSON数据并在html中显示。我能够使用jQuery .ajax()连接到servlet,但无法检索json值。

以下是我的html示例

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="javascript/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// click function

$('#btn').click(function(){

 // get the request

 /*

      $.ajax({url:'JsonCreationOfUrlAndContent',
             type:"GET",
             dataType:"json",
             asyn:true,
             success:function(data)
             { 

             $("div#main").text(data.Trends[1].title);}

      });


    */

    //now using getJSON

    $.getJSON('JsonCreationOfUrlAndContent',function(data)
            {
        $("div#main").html(data.Trends[1].title);
            });

        });

});


</script>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input id="btn" type="button" name="test" value="PressME"></input>
<div id="main">


</div>
</body>
</html>

下面是我的java代码,我正在创建一些结构的样本JSON,如下面的

{"Trends":[
     {"url":"http://google.com",
      "title":"No#1 Search Engine"},
     {"url":"http://bing.com",
     "title":"Best socal search engine"},
   {"url":"http://altavista.com",
   "title":"Oldest search engine"}]}

以下是我的java代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        PrintWriter pw =(PrintWriter)response.getWriter();
        // create the JSONObject

        JSONObject jobj1 = new JSONObject();
         jobj1.put("url","http://google.com");
         jobj1.put("title","No#1 Search Engine");

         JSONObject jobj2 = new JSONObject();
         jobj2.put("url","http://bing.com");
         jobj2.put("title","Best socal search engine");

         JSONObject jobj3 = new JSONObject();
         jobj3.put("url","http://altavista.com");
         jobj3.put("title","Oldest search engine");

         JSONArray jarr = new JSONArray();
          jarr.add(jobj1);
          jarr.add(jobj2);
          jarr.add(jobj3);

          // now add JSONArrayO to JSONObject

          JSONObject fObj = new JSONObject();
          fObj.put("Trends",jarr);

          pw.println(fObj);


    }

2 个答案:

答案 0 :(得分:1)

asyn:true

应该是

async:true

答案 1 :(得分:1)

您是否检查过您是否真的使用firebug收到了json响应?

我认为您的评论代码是工作版本。在您评论的行中,有这一行:

$("div#main").text(data.Trends[1].title);

但在没有评论的那篇文章中,这一行有点不同:

$("div#main").html(data.Trends[1].title);

也许这就是原因?