gpt4 book ai didi

javascript - 如何将数组写入的字符串转换为真正的数组?

转载 作者:行者123 更新时间:2023-11-28 15:48:36 26 4
gpt4 key购买 nike

我有这个:

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 变量如何是数组?有没有办法将字符串转换为数组而不更改字符串值/文本?

最佳答案

将你的ajax设置为具有类似dataType:"json"的属性,这样它就会自动将返回的字符串转换为对象,否则你需要使用data_chart = JSON.parse(数据图表);

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

关于javascript - 如何将数组写入的字符串转换为真正的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21372617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com