简体   繁体   English

JSON.parse:意外的角色

[英]JSON.parse: unexpected character

I'm trying to pass a json from php jquery, after getting into an array of sql query and get the following javascript error. 我试图从php jquery传递一个json,在进入一个sql查询数组后得到以下javascript错误。

JSON.parse: unexpected character

The function to return result of sql: 返回sql结果的函数:

public function selectassocSql($sql){
$i = 0;
        $resSelect = array();
        mysql_query("SET NAMES 'utf8'");
        $result = mysql_query($sql);
        while ( $row = mysql_fetch_assoc($result) )
        {
            $resSelect[$i] = $row;
            $i++;
        }
        mysql_free_result($result);
        return $resSelect;
}

After use this function in this way, 以这种方式使用此功能后,

$sql = "SELECT id, code, name FROM table WHERE code LIKE '%$codcli%' ";
$v = $data->selectassocSql($sql);
echo json_encode($v, JSON_FORCE_OBJECT); 

And the javascript code is this: 而javascript代码是这样的:

$('#formclientes').submit(function(e){

        e.preventDefault();
        $.ajax({
            type: 'POST',
            url:$(this).attr('action'),
            data:$(this).serialize(),
            success:function(data)
            {
              //console.log("SUCCESS " + data);
              var json_cli = $.parseJSON(data);
            }
        })
    })   

How I can correct this error and how I can read a json from jquery? 我如何纠正这个错误以及如何从jquery读取json?

You don't need the $.parseJSON call as jQuery automatically does it because if you don't specify a dataType property jQuery tries to guess it and calls the correct function to parse the response before the data is handled to the success function 您不需要$.parseJSON调用,因为jQuery会自动执行此操作,因为如果您未指定dataType属性,jQuery会尝试猜测它并调用正确的函数来解析响应,然后将数据处理到success函数

   $.ajax({
        type: 'POST',
        url:$(this).attr('action'),
        data:$(this).serialize(),
        success:function(data)
        {
          //console.log("SUCCESS " + data);
          var json_cli = data;
        }
    })

check out also this question Why is 'jQuery.parseJSON' not necessary? 看看这个问题为什么'jQuery.parseJSON'没有必要?

I just ran into this in FF10.0.2 with data that looked like: 我刚刚在FF10.0.2中遇到过这样的数据:

[ { "firstName": 'Joe', "lastName": 'Smith' } ]

(with multiple objects in the array - shortened for clarity) (在阵列中有多个对象 - 为了清晰起见缩短了)

It actually parsed OK using eval, though, instead of JSON.parse. 它实际上使用eval解析了OK,而不是JSON.parse。 (I'm not using jQuery here.) (我这里不使用jQuery。)

The problem went away when I changed ' to " for the values: 当我将值改为'to'时,问题就消失了:

[ { "firstName": "Joe", "lastName": "Smith" } ]

I thought the " requirement was only for property names, not data values. 我认为“要求仅适用于属性名称,而不是数据值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM