【问题标题】:data transfer using JSON使用 JSON 传输数据
【发布时间】:2011-04-17 10:56:18
【问题描述】:

我正在尝试使用 JSP 技术从服务器获取一条数据。我正在使用 JSON 对象来做到这一点。在客户端,我使用 XMLHttpRequest 来获取数据。

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

<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);

%>

很遗憾,我无法得到回复。

【问题讨论】:

标签: javascript ajax json jsp xmlhttprequest


【解决方案1】:

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

不要那样做。响应应该只是 JSON。

【讨论】:

    【解决方案2】:

    您需要使用内容类型 application/json 编写。

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

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

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

    JSON.parse(string).   
    

    但不要使用 eval

    【讨论】:

    • 当我将内容类型设置为 json 时,是否需要将 json 对象转换为字符串...和thanx 寻求帮助
    猜你喜欢
    • 2012-02-08
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 2012-09-01
    相关资源
    最近更新 更多