[英]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.