2011-04-17 43 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