javascript JSON.parse:意外字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9688870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.parse: unexpected character
提问by vllopico
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?
回答by Nicola Peluchetti
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 会尝试猜测它并调用正确的函数来解析响应,然后再将数据处理为成功函数
$.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?
回答by SteveC
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. (I'm not using jQuery here.)
不过,它实际上使用 eval 解析,而不是 JSON.parse。(我在这里没有使用 jQuery。)
The problem went away when I changed ' to " for the values:
当我将 ' 更改为 " 值时,问题就消失了:
[ { "firstName": "Joe", "lastName": "Smith" } ]
I thought the " requirement was only for property names, not data values.
我认为“要求仅适用于属性名称,而不是数据值。