求助:如何将AJAX查询结果存入另一个对象?代码问题排查
问题解决方法
你的代码里有两个关键错误,导致无法把AJAX查询结果存入目标结构:
误用对象调用数组方法
你把results1定义成了对象var results1 = {};,但push是数组的专属方法,对象没有这个方法。必须改成数组类型:var results1 = [];对象字面量语法错误
你写的{response.d.Rows[i][0], response.d.Rows[i][1]}不符合JavaScript对象的语法规则,对象需要明确的键值对结构。如果要存储键值对,得给每个值指定键名,比如:results1.push({ id: response.d.Rows[i][0], content: response.d.Rows[i][1] });如果只是想存两个值的集合,直接用数组更合适:
results1.push([response.d.Rows[i][0], response.d.Rows[i][1]]);
修正后的完整代码:
$.ajax({ type: 'POST', url: '/Orion/Services/Information.asmx/QueryWithParameters', data: params, contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (response) { var results1 = []; // 改为数组 for (var i = 0; i < response.d.Rows.length; i++) { // 根据需求选择键值对或数组格式 results1.push({ key: response.d.Rows[i][0], value: response.d.Rows[i][1] }); // 或者用数组:results1.push([response.d.Rows[i][0], response.d.Rows[i][1]]); } console.table(results1); }, });
内容的提问来源于stack exchange,提问作者dinith tharuka
相关产品推荐
相关产品推荐

