我有这个:
var chart = {
chart_bar :
data : [{label:"A", data:[[0, 5], [1, 1]]}]
}
data
变量必须是数组。我通过ajax传递了一个变量。变量的值为{label:"C", data:[[0, 4], [1, 3]]}
,我将其分配给data
变量,然后脚本不起作用。
PHP:
function get_data(){
echo '{label:"C", data:[[0, 4], [1, 3]]}';
}
的javascript:
$.ajax({
url : "..../get_data", //no problem with the url
data: "data="+somedata,
type: "post",
success : function(data_chart){
var chart = {
chart_bar :
data : [ data_chart ] // and the program doesn't work
init : function(){
alert(data_chart.toSource()); // it says (new String("{label:"C", data:[[0, 4], [1, 3]]}")), so the data_chart is a string
}
}
}
});
但如果我设置
var chart = {
chart_bar :
data : [ {label:"C", data:[[0, 4], [1, 3]]} ] // and the program works
init ; function(){
alert(this.data.toSource()); // it says [ {label:"C", data:[[0, 4], [1, 3]]} ], so this is an array
}
data_chart
变量如何成为一个数组?有没有办法将字符串转换为数组而不更改字符串值/文本?
答案 0 :(得分:2)
将你的ajax设置为具有dataType:"json"
之类的属性,这样它会自动将返回的字符串转换为对象,否则你需要使用data_chart = JSON.parse(data_chart);
PHP
function get_data(){
//note this is not proper json format
echo '{label:"C", data:[[0, 4], [1, 3]]}';
//should be
echo '{"label":"C","data":[[0,4],[1,3]]}';
}
另请注意,您可以使用php的json_encode(如echo json_encode($objOrArray)
)来回显对象或数组的json字符串
JS
$.ajax({
url : "..../get_data", //no problem with the url
data: "data="+somedata,
type: "post",
dataType:"json",
success :
function(data_chart){
//if valid JSON string was returned from the php script data_chart will be an object
var chart = {
chart_bar :
data : [ data_chart ],
init : function(){
alert(data_chart.toSource());
}
}
}
});
答案 1 :(得分:2)
最好的办法是使用PHP的json_encode()函数生成格式正确的JSON数据,然后使用JSON.parse()或@Patrick Evans的jQuery建议来读取JS中的数据。
PHP:
$data = array();
$data['label'] = "C";
$data['data'] = [[0,4],[1,3]];
print json_encode($data);