我想在我访问的对象中向数组添加元素以检索数据。
var event_id = events_data.event_id[i]["0"];
var event_title = events_data.event_title[i]["0"];
var selected_source = events_data.selected_source[i]["0"];
var channel_id = events_data.channel_id[i]["0"];
events_data是一个带有元素event_id,event_title,...的对象。该对象是在这样的php函数中创建的。
$return = array();
$return['event_id'] = $event_id;
$return['event_title'] = $event_title;
$return['selected_source'] = $selected_source;
$return['channel_id'] = $channel_id;
$return['channel_name'] = $channel_name;
$return['event_site'] = $event_site;
$return['event_url'] = $event_url;
$return['start_date'] = $start_date;
$return['start_time'] = $start_time;
$return['end_date'] = $end_date;
$return['end_time'] = $end_time;
$return['event_notes'] = $event_notes;
echo json_encode($return);
编辑 - 添加信息
json对象看起来像这样。
{ “事项标识”:[{ “0”: “e20120319215556”},{ “0”: “e20120310221512”},{ “0”: “e20120319151903”},{ “0”: “e20120309123705”},{ “0”: “e20120307122044”},{ “0”: “e20120306182514”},{ “0”: “e20120309211714”},{ “0”: “e20120314130727”},{ “0”: “e20120319150532”},{ “0”: “e20120319141928”},{ “0”: “e20120319141201”},{ “0”: “e20120301193226”},{ “0”: “e20120301184354”}]}
END INFO ADDED
在javascript方面,我得到了像这样的events_data数组。
$.ajax({
url: "get_events_data.php",
type: "POST",
dataType : 'json',
data: { },
cache: false,
async: false,
success: function (rdata) {
events_data = rdata;
}
});
要在javascript端向events_data添加元素,我检查索引在哪里添加新元素,然后使用splice添加它。但由于使用关联数组的[“0”]文本键检索数据,我不知道如何指定splice参数。
for ( var n=0; n<events_data.event_id.length; n++ ) {
if ( current_event_id == events_data.event_id[n]["0"] ) {
//splice_index = n;
events_data.event_id.splice(n,0,event_id);
events_data.event_title.splice(n,0,event_title);
events_data.selected_source.splice(n,0,selected_source);
events_data.channel_id.splice(n,0,channel_id);
events_data.channel_name.splice(n,0,channel_text);
events_data.event_site.splice(n,0,event_site);
events_data.event_url.splice(n,0,event_url);
events_data.start_date.splice(n,0,start_date_string);
events_data.start_time.splice(n,0,start_time_string);
events_data.end_date.splice(n,0,end_date_string);
events_data.end_time.splice(n,0,end_time_string);
events_data.event_notes.splice(n,0,event_notes);
break;
}
}
指定拼接索引“n”似乎没有这样做。我应该改变什么?
感谢。
答案 0 :(得分:1)
答案很简单:
Adding an object to an array of objects with splice
var add_object = {"0",event_id}; // declare event id as object
events_data.event_id.splice(n,0,add_object); // splice object into object array at index