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

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

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

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

 {success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"} 

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

     $(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 = 'https://localhost:8080/QuoteroClient/logged.jsp'; }else{ alert("Something went wrong in the login process."); } return false; }); });    
Login to Quotero:



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

 $("#ajaxSubmit").click(function () { $.ajax({ type: "GET", //GET or POST is the same for this servlet url: "https://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 + 'https://localhost:8080/QuoteroClient/logged.jsp'; } else { alert("Something went wrong in the login process."); } } }); return false; }); 

    我认为你把ajax与提交混淆了。 提交只是一个事件,当提交表单时执行以下操作。 然后你可以

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

    这不是有效的JSON:

     {success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"} 

    这是有效的JSON:

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

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

    需要了解更多jQuery教程分享JSON响应作为文件打开,但我无法使用JavaScript访问它,都可以关注jQuery技术分享栏目—计算机技术网(www.ctvol.com)!

      以上就是jQuery教程分享JSON响应作为文件打开,但我无法使用JavaScript访问它相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/jquerytutorial/981669.html

      (0)
      上一篇 2021年12月12日
      下一篇 2021年12月12日

      精彩推荐