简体   繁体   English

通过$ .post问题发送数组到PHP

[英]sending array to PHP via $.post issue

I have an issue when sending to server array in POST via ajax with JQuery version is 1.10.2 . 通过带有JQuery版本为1.10.2 ajax在POST中发送到服务器数组时出现问题。 My array is array of objects (such object is basically an associative array). 我的数组是对象数组(此类对象基本上是关联数组)。

Function JSON.stringify(word_mean_arr); 函数JSON.stringify(word_mean_arr); return [[]] - so it fail to work and if I simply write: 返回[[]] -因此它无法正常工作,如果我简单地写:

$.post( "./ajax2/myscript.php", {block_id: bl_id, wm_arr: word_mean_arr})

I cannot get value of $POST['wm_arr'] like it does not exist. 我无法获取$ POST ['wm_arr']的值,因为它不存在。

Example of my array is something like: 我的数组的例子是这样的:

[[key]=>1,[value]=>"this_is_"],[[key]=>2,[value]=>"this_is_str2"]

So my object is: 所以我的对象是:

[  [key]=>1,   [value]=>"this_is_str"]

This is how I form my array 这就是我形成数组的方式

var word_mean_arr = new Array();
for (var i = 0; i <= this.n_of_wd_mean; i++)
{
    var temp_arr = new Array();
    temp_arr['key'] = $("#tswes_2_"+i).val();
    temp_arr['value'] = $("#tswes_2_"+i).val();
    word_mean_arr.push(temp_arr);
}
console.log("Array to server length>" + word_mean_arr.length);
var jsonString = JSON.stringify(word_mean_arr);

How should I transfer data and what is the problem? 我应该如何传输数据,这是什么问题?

UPDATE 1: JSON.stringify(temp_arr) is [] , but when console.log(word_mean_arr) I see whole structure of my array. 更新1: JSON.stringify(temp_arr)[] ,但是当console.log(word_mean_arr)我看到了数组的整个结构。

UPDATE 2: Replacing temp_arr['key'] with temp_arr[0] , solves my problem. 更新2:temp_arr['key']替换为temp_arr[0]解决了我的问题。 But still qurious how to send key->val. 但是仍然好奇如何发送key-> val。

Your temp_arr variable is initialized as an array, but then you work with it as with an object, accessing keys that it does not have. 您的temp_arr变量被初始化为数组,但随后您将其与对象一起使用,访问它没有的键。

This will solve the problem: 这将解决问题:

var temp_arr = {
    key: $("#tswes_2_"+i).val(),
    value: $("#tswes_2_"+i).val()
};

instead of this: 代替这个:

var temp_arr = new Array();
temp_arr['key'] = $("#tswes_2_"+i).val();
temp_arr['value'] = $("#tswes_2_"+i).val();

Simply don't use JSON.stringify , jQuery does encode the variables itself when using $.post . 只需不使用JSON.stringify ,jQuery就可以在使用$.post时对变量本身进行编码。

var word_mean_arr = $('.tswes').serialize();
console.debug('sending: ');
console.debug(word_mean_arr);
$.post('./ajax2/myscript.php', { block_id: bl_id, wm_arr: word_mean_arr });

If it does not work, try different: 如果不起作用,请尝试其他操作:

var word_mean_arr = [];
for (var i = 0; i <= this.n_of_wd_mean; i++)
{
    var temp_arr   = {};
    temp_arr.key   = $("#tswes_2_"+i).val();
    temp_arr.value = $("#tswes_2_"+i).val();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM