0

我有这个包含数组的数组对象:

var webApps = [
    ['leave empty']
];

我正在对一些内容进行 ajax 处理,最终的 ajax 结果字符串将是这样的:

ajaxResult = ',["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]';

我的问题是,如何获取返回的字符串并将其添加到 webApps 数组中?

4

5 回答 5

1

正如@Bergi 指出的那样,让您的ajax电话返回有效可能是个好主意JSON。如果这不是您可以控制的,那么您需要将其转换为 valid JSON,解析它,然后concat转换为webApps数组:

var webApps = [
    ['leave empty']
];

var ajaxResult = ',["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]';

//strip the comma
ajaxResult = ajaxResult.substring(1);

//surround with []
ajaxResult = "[" + ajaxResult + "]";

//parse
ajaxResult = JSON.parse(ajaxResult);

//and concat
webApps = webApps.concat(ajaxResult);
于 2013-08-01T02:54:22.693 回答
0

首先将结果转换为可解析的东西(我希望不需要其他怪癖):

var jsonStr = "["+ajaxResult.slice(1)+"]";
// [["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]]
// would be better if it looked like that in the first place

现在我们可以解析它,并将单个项目推送到您的数组中:

var arr = JSON.parse(jsonStr);
webApps.push.apply(webApps, arr);

我们也可以使用循环,但push可以接受多个参数,这样更容易apply

于 2013-08-01T02:54:22.197 回答
0

如果浏览器支持 JSON,则以下内容有效。

var webApps = [
    ['leave empty'],['one']
];
var str = JSON.stringify(webApps);
// "[["leave empty"],["one"]]"

str = str.substr(0, str.length-1);
//"[["leave empty"],["one"]"

//var arr = eval(str + ajaxResult + "]");
// more secure way
var arr = JSON.parse(str + ajaxResult + "]");
于 2013-08-01T02:56:52.917 回答
0

webApps = eval("[['"+(webApps[0]).toString()+"']"+ajaxResult+"]");

这很奇怪,但请解决您的问题。

于 2013-08-01T03:29:30.700 回答
-1

如果 ajax 结果是一个字符串,您可以将其转换为对象并将每个属性添加到 webapps var。

var data = eval('(' + ajaxResult + ')'); // data is a javascript array now, do anything you want
于 2013-08-01T02:55:42.337 回答