开发者

Problem understanding javascript multi-dimension arrays

I want to get some values out of TinyMCE textboxes, along with IDs. Then post these via ajax to the server.

jQuery 1.4 and JSON library are loaded

var send_data = [];

$('.contact_check').each(function(i, item) {
  var this_id = $(item).attr('id');
  var msgbox = tinyMCE.get('contacts[' + this_id + '][message]');
  var content = addslashes(msgbox.getContent());
  send_data[i]["id"] = this_id;
  send_data[i]["conte开发者_如何学Cnt"] = escape(content);
});

var encoded = JSON.stringify(send_data);

$.ajax({
  type: 'POST',
  url: 'http://localhost/test.php',
  data: encoded,
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: function() {
    alert('jay');
  }
});

Firstly,

send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);

does not seem to work. It says send_data[i] undefined. I've also tried:

send_data[this_id] = escape(content);

That does not seem to work either. The JSON string returns as []. What am I doing wrong?


You're not really making a multi-dimensional array. You're making an array of objects. Either way, before you can set an attribute or array element of something at send_data[i], you have to make send_data[i] be something.

send_data[i] = {};
send_data[i]['id'] = this_id;
send_data[i]['content'] = escape(content);

or, better:

send_data[i] = {
  id: this_id,
  content: escape(content)
};


You have to make each send_data[i] an object first:

 $('.contact_check').each(function (i, item) {
    var this_id = $(item).attr('id');
    var msgbox = tinyMCE.get('contacts['+this_id+'][message]');
    var content = addslashes(msgbox.getContent());
    send_data[i] = {};
    send_data[i]["id"] = this_id;
    send_data[i]["content"] = escape(content);
  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜