JSON 响应作为文件打开,但我无法使用 JavaScript 访问它

发布于 2024-10-20 03:27:58 字数 2981 浏览 1 评论 0原文

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

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

In the code below I make a POST request to a servlet that replies in this way:

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

So Firefox opens it like a file and I can see it's ok. Here you have the JSON:

{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}

The problem is that I can't inspect the JSON object. It seems not to exist inside my callback function (also using Firebug). Take a look to the code and alerts.

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

EDIT: I also tried to do the same with an AJAX request, wothout success:

$("#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;
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

生生漫 2024-10-27 03:27:58

这是无效的 JSON:

{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}

这是有效的 JSON:

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

在 JSON 中,必须始终用引号引起来的键。请参阅演示

This is not valid JSON:

{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}

This is valid JSON:

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

In JSON the keys must always be quoted. See DEMO.

不念旧人 2024-10-27 03:27:58

我认为您混淆了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;
 });

I think you have mixed up ajax with submit. submit is just simply an event, when form is submitted do the following. then you can

 $("#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;
 });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文