I have this array object that contains arrays:
var webApps = [
['leave empty']
];
I'm ajaxing in some content and the end ajax resulting string will be something like this:
ajaxResult = ',["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]';
My question is, how do I take the returned string and add it to the webApps array?
As @Bergi pointed out, it would probably be a good idea to make your ajax
call return valid JSON
. If thats not something you have control over, then you need to turn it into valid JSON
, parse it, and concat
to the webApps
array:
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);
First transform the result into something that is parseable (I hope no other quirks is necessary):
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
Now we can parse it, and push the single items on your array:
var arr = JSON.parse(jsonStr);
webApps.push.apply(webApps, arr);
We could've used a loop as well, but push
can take multiple arguments so it's easier to apply
it.
The following works if the browser supports 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.