2011-04-17 72 views
0

我想从使用JSP技术的服务器获取一段数据。我正在使用JSON对象来这样做。在客户端,我使用XMLHttpRequest来获取数据。使用JSON进行数据传输

要检查它是否正常工作,我写了一段代码如下:

<head> 
<script type="text/javascript"> 
      function test(data) { 
if(data){ 
    var jsonObj= eval('(' + data + ')'); 
    var Question= jsonObj.Question; 
    document.write(Question); 
} 
} 

function handler() { 
if(this.readyState == 4 && this.status == 200) { 
    // so far so good 
    if(this.responseText != null && this.responseText) 
    // success! 
    test(this.responseText); 
    else 
    test(null); 
} else if (this.readyState == 4 && this.status != 200) { 
    // fetched the wrong page or network error... 
    test(null); 
} 
} 
function xyz(){ 
var client = new XMLHttpRequest(); 
client.onreadystatechange = handler; 
client.open("POST", "fetch.jsp", true); 
client.send(); 
} 
     </script> 

    </head> 
    <body> 
     <h1>Hello World!</h1> 
     <br><br><input id="Q" type="button" onclick="xyz()" > 
    </body> 

服务器端的我做了如下:

<%@page import="net.sf.json.JSONObject"%> 
<%@page contentType="text/html" pageEncoding="UTF-8"%> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>JSP Page</title> 
    </head> 
    <body> 

     <% JSONObject jsonObj= new JSONObject(); 
      jsonObj.put("Question","What is your name?"); 
      jsonObj.put("Opt1","ji"); 
      jsonObj.put("Opt2","ji"); 
      jsonObj.put("opt3","ma"); 
      jsonObj.put("opt4","sa"); 

     String str= jsonObj.toString(); 
     response.setContentType("text/plain"); 
     response.getWriter().write(str); 

%> 

可惜我没能拿到响应。

+0

'文/ plain'应该是'应用程序/ json' – Quentin 2011-04-17 11:17:55

+0

不要使用'eval',得到适当的JSON解析器:https://github.com/douglascrockford/JSON-js – Quentin 2011-04-17 11:18:15

回答

1

您正在将您的JSON写入HTML文档的正文,然后发送HTML文档作为响应。

不要这样做。响应应该是只是的JSON。

0

你需要写内容类型application/json。

也不要在测试函数中使用eval。

当数据是json时,测试函数可以作为json对象访问数据!

在解析字符串的情况下使用。

JSON.parse(string). 

但不要使用eval

+0

当我设置内容类型为json时,是否需要将json对象转换为字符串... 和thanx帮助 – jigish 2011-04-18 09:34:21

+0

thanx很多帮助 – jigish 2011-04-18 10:34:40

+0

很高兴工作。 – 2011-04-18 10:43:27