[英]Adding string to an array filled with arrays
我有这个包含数组的数组对象:
var webApps = [
['leave empty']
];
我正在对某些内容进行 ajaxing,最终的 ajax 结果字符串将是这样的:
ajaxResult = ',["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]';
我的问题是,如何获取返回的字符串并将其添加到 webApps 数组中?
正如@Bergi 指出的那样,让您的ajax
调用返回有效的JSON
可能是个好主意。 如果这不是您可以控制的,那么您需要将其转换为有效的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);
首先将结果转换为可解析的内容(我希望不需要其他怪癖):
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);
如果浏览器支持 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 + "]");
webApps = eval("[['"+(webApps[0]).toString()+"']"+ajaxResult+"]");
这很奇怪,但解决你的问题。
如果 ajax 结果是字符串,您可以将其转换为对象并将每个属性添加到 webapps var。
var data = eval('(' + ajaxResult + ')'); // data is a javascript array now, do anything you want
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.