【问题标题】:JSON response opens as a file, but I can't access it with JavaScriptJSON 响应作为文件打开,但我无法使用 JavaScript 访问它
【发布时间】:2011-03-03 12:35:36
【问题描述】:

在下面的代码中,我向以这种方式回复的 servlet 发出 POST 请求:

response.setContentType("application/json");
json = "{success:true,sessionUid:\""+sessionUid+"\"}";
response.getWriter().write(json);

所以 Firefox 像打开文件一样打开它,我可以看到它没问题。这里有 JSON:

{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}

问题是我无法检查 JSON 对象。它似乎不存在于我的回调函数中(也使用 Firebug)。查看代码和警报。

<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("#loginForm").submit(function(response){
alert("response="+response);    //output: "response=[object Object]"
                    var obj = jQuery.parseJSON(response);
alert("obj.sessionUid="+obj.sessionUid);    //doesn't work, Firebug says "obj is null"
                    if (response.success == true){ //never true
                        document.location.href = 'http://localhost:8080/QuoteroClient/logged.jsp';
                    }else{
                        alert("Something went wrong in the login process.");
                    }
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <form id="loginForm" action="http://localhost:8080/QuoteroClient/Main?servlet=Security" method="post">
            <fieldset><legend>Login to Quotero:</legend>
                <label>Action:</label><input type="text" name="action" value="login"/><br />
                <label>Username:</label><input type="text" name="login-quotero" value="admin"/><br />
                <label>Password:</label><input type="text" name="password-quotero" value="admin" /><br />
                <label>Domain:</label><input type="text" name="combo-domain" value="Quotero" /><br />
            </fieldset>
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

编辑:我也尝试对 AJAX 请求做同样的事情,但没有成功:

$("#ajaxSubmit").click(function () {
  $.ajax({
    type: "GET", //GET or POST is the same for this servlet
    url: "http://localhost:8080/QuoteroClient/Main?servlet=Security&action=login&login-quotero=admin&password-quotero=admin&combo-domain=Quotero",
    dataType: "json",
    success: function (response) {
alert("response=" + response);
      var obj = jQuery.parseJSON("" + response);
alert("obj.sessionUid=" + obj.sessionUid);
      if (response.success == true) {
        document.location.href = contextPath + 'http://localhost:8080/QuoteroClient/logged.jsp';
      } else {
        alert("Something went wrong in the login process.");
      }
    }
  });
  return false;
});

【问题讨论】:

  • 我不明白如果你使用萤火虫为什么要使用alert()?使用console.log(response); 这样您就可以像文件树一样查看甚至导航json对象
  • 我认为你的问题可能在这条线上var obj = jQuery.parseJSON(response); 我认为响应返回为 jquery 反正不需要再次解析它。
  • 您是否要将此作为 ajax 请求?因为否则提交只是一个事件处理程序而不是 ajax 请求。
  • @Val 感谢console.log(),对我来说是新东西!我尝试将其作为 AJAX 请求进行,但没有成功。现在我尝试编辑问题。
  • 删除?servlet=Security&amp;action=login&amp;login-quotero=admin&amp;password-quotero=admin&amp;combo-domain=Quotero 并使用data 选项在我的回答告诉你如何serialize 它,也看看serializeArray

标签: javascript jquery json response


【解决方案1】:

这是无效的 JSON:

{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}

这是有效的 JSON:

{"success":true,"sessionUid":"D07WC15R7LFRFRGPF4P5"}

在 JSON 中,必须始终引用键。见DEMO。

【讨论】:

  • 没有必要用引号对键进行转义,除非它们与 CLASS、FOR 等预定义值发生冲突。
  • 这并不完全正确,引号是可选的,但是当某些名称与本机 javascript 关键字(例如delete 等等...
  • @Nazariy:总是需要在 JSON 中引用键。见the spec。
  • @bluish:这是一个问题,因为在 JSON 中每个键都必须被引用。请参阅上面评论中的演示。
  • @Val:我当然是认真的。 jQuery.ajax 内部使用 jQuery.parseJSON 并且 parseJSON 需要格式良好的 JSON,每个键周围都有强制引号。请参阅api.jquery.com/jQuery.parseJSON 的文档,因为它解释得很好。
【解决方案2】:

我认为您将 ajax 与提交混淆了。 submit 只是一个简单的事件,当提交表单时,请执行以下操作。那么你可以

 $("#loginForm").submit(function(){
     var post_data = $(this).serialize();
     $.ajax({
        url: '',//url of the php file that handles the forms
        type: 'GET',
        dataType:'json',
        data:post_data,//this are the query strings, e.g. ?q=blabla&s=blabla
        success:function (data){//if page was 200 or successfully loaded
             alert(data.sessionUid);
             // do what ever you wish with the data here
        },
        error: function (){
            alert('Page failed to load');
        }
     })
     return false;
 });

【讨论】:

  • @Val 谢谢,你很有用。无论如何,我按照你说的做了,但不能让它工作。结果是错误警报
  • 那你就知道网址不对了。在firebug 上显示什么数字?单击提交后,在net 选项卡上的status 部分上,应该会出现一个带有状态代码的网址
  • 老实说,我对 asp.net 的经验为零,但这也可以帮助你。 stackoverflow.com/questions/579053/… 对数组中的 json 进行编码,除非您使用的是 json_encode($array) 的 php
  • URL 正常,状态为 200 OK,但网络 > 回复选项卡为空.. ASP 还是 PHP?我正在使用 Java servlet。
  • 好的,页面没问题,问题是你的页面返回纯文本,你需要json我做了一点谷歌,发现这个objectmix.com/javascript/…可能有帮助,虽然我没有关于java的线索。但如果有任何谷歌 java servlets 数组到 json 或类似的东西
猜你喜欢
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
相关资源
最近更新 更多