zoukankan      html  css  js  c++  java
  • jQuery解析JSON出现SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

    SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

    我在使用$.parseJSON解析后台返回的JSON的数据时,出现了这样的错误,我还以为返回的JSON格式出现了错误,因为JSON要求格式非常严格。最后发现JSON格式没有太明显的格式错误,我使用fastJSON来生成的JSON格式数据,原来是因为数据已经是一个JavaScript对象了,所以在进行解析就会出错了

    我直接将这段数据alert出来,并使用typeof检验其类型,发现是一个Object,这就证明了数据已成为了JavaScript对象了。所以,我直接使用(不用什么parseJSON解析了)这段数据进行相应的处理就不会出错

       $.ajax({
                 url : 'commentAction_showComment',
                 type : 'POST',
                 data:{
                          titleid: $(comment_this).attr('data-id'),         
                          currPage : currPage,
                      },
                 beforeSend : function (jqXHR, settings) {
                      $('.comment_list').eq(index).append('<dl class="comment_load"><dd>正在加载评论</dd></dl>');
                 },
                 success : function (response, status) {
                      var json_comment = response;
                 },
         });

    也许是我对jQuery的parseJSON方法理解错误使用不当,或者是该用其他的方法处理?

    后台响应的是JSON格式的字符串而不是JSON对象

    如果后台发送的是一个JSON格式的字符串(注意:是字符串,只是采用JSON的语法格式,不是JSON数据),我们在前台应该怎样解析成一个JSON对象呢?

    后台代码:

            PrintWriter out = response.getWriter();
            String username = request.getParameter("user");
            String password = request.getParameter("pwd");
            String data = "{'username':'"+username+"','password':'"+password+"'}";
            System.out.println(data);
            out.write(data);

    这个data就是一个JSON格式的字符串

    我们需要将eval()方法将这个字符串包一下,就可以转成JSON对象了,eval应该是一个JavaScript中的方法:

    $.ajax({ //一个Ajax过程 
                type : "post", //以post方式与后台沟通 
                url : "Ajax_jQueryServlet", //与此php页面沟通 
                data : 'username=' + username + '&password=' + password, 
                success : function(data) { 
                    var json = eval('(' + data + ')');
                    $('#result').html(
                            "姓名:" + json.username + "<br/>密码:" + json.password); 
                }
            });

     注:eval('('+text+')')将JSON格式的字符串text解析为成具体的类型,如boolean什么的,有时可能需要使用eval('['+text+']')  方括号来包裹JSON字符串,可以解析为数组,也就是Object类型。具体使用看情况吧

  • 相关阅读:
    Matlab 绘制三维立体图(以地质异常体为例)
    Azure DevOps的variable group实现array和hashtable参数的传递
    Azure DevOps 利用rest api设置variable group
    Azure AADSTS7000215 其中一种问题的解决
    Power BI 实现实时更新Streaming Dataset
    AAD Service Principal获取azure user list (Microsoft Graph API)
    Matlab 沿三维任意方向切割CT图的仿真计算
    Azure Powershell script检测登陆并部署ARM Template
    Azure KeyVault设置策略和自动化添加secrets键值对
    Azure登陆的两种常见方式(user 和 service principal登陆)
  • 原文地址:https://www.cnblogs.com/lz2017/p/6937499.html
Copyright © 2011-2022 走看看