JSON.parse:意外的角色 [英] JSON.parse: unexpected character

查看:134
本文介绍了JSON.parse:意外的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从php jquery传递json,在进入sql查询数组后得到以下javascript错误。

I'm trying to pass a json from php jquery, after getting into an array of sql query and get the following javascript error.

JSON.parse: unexpected character

返回sql结果的函数:

The function to return result of 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); 

javascript代码如下:

And the javascript code is this:

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

如何更正此错误以及如何从jquery读取json?

How I can correct this error and how I can read a json from jquery?

推荐答案

您不需要将 $。parseJSON 自动调用为jQuery这样做是因为如果你没有指定 dataType 属性,jQuery会尝试猜测它并调用正确的函数来解析响应,然后将数据处理成成功函数

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

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

也请查看此问题为什么'jQuery.parseJSON'没有必要?

这篇关于JSON.parse:意外的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆