Javascript JSON.parse:意外字符错误 [英] Javascript JSON.parse: unexpected character error
问题描述
我想从php脚本中获取一个字符串,并将其解析为javascript数组.但出现错误: SyntaxError:JSON.parse:意外字符为行:JSON.parse(msg);
I want to get a string from a php script, and parse it to a javascript array. but got the error : SyntaxError: JSON.parse: unexpected character for the line :JSON.parse(msg);
我搜索了很多,无法弄清楚我的问题出在哪里,请帮忙检查一下.谢谢.
I searched a lot , couldn't figure out where is my problem, please help check for me. Thanks.
PHP方面:
header("application/json; charset=utf-8");
$sum = array(1,2,3,4,5);
echo json_encode($sum);
JavaScript:
Javascript :
$.ajax({
type: "POST",
url: "save.php",
contentType: "application/json; charset=utf-8",
data: price,
success: function (msg) {
var i = 0;
console.log(msg);
var sum = new Array();
sum = JSON.parse(msg);
$('input.hj').each(function () {
if (sum[i] > 0) {
$(this).val(sum[i]);
}
i++;
});
}
});
推荐答案
不要解析它:$.ajax
为您解析了它.只需使用为您的success
回调函数提供的参数,这就是已解析的数组.
Don't parse it : $.ajax
parsed it for you. Just use the argument which is given to your success
callback, this is the parsed array.
如果您的浏览器无法检测到它的JSON,请添加dataType
参数.
If your browser can't detect it's JSON, add the dataType
argument.
还请注意,您不必自己管理i
计数器:一个由each
传递:
Note also that you don't have to manage the i
counter yourself : one is passed by each
:
dataType: 'json',
success: function(sum){
$('input.hj').each(function(i){
if (sum[i] > 0) {
$(this).val(sum[i]);
}
});
}
这篇关于Javascript JSON.parse:意外字符错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!