简体   繁体   English

关联数组作为空字符串传递

[英]Associative array passing as empty string

I am trying to pass an array to PHP via Ajax, but the array is being passed as an empty string. 我试图通过Ajax将数组传递给PHP,但是该数组作为空字符串传递。 This is my code when creating the array: 这是创建数组时的代码:

var params = new Array();
var inputs = new Array();
inputs = $(":input");
$.each(inputs, function(key, value) {
  params[value.id] = value.value;
});

alert(params);

Before that there are around 20 inputs that look like this: 在此之前,大约有20个输入如下所示:

<input name="first_name" id="first_name" type="text" class="medium"/>
<input name="last_name" id="last_name" type="text" class="medium"/>

The alert(params) is just giving me an empty string. alert(params)只是给我一个空字符串。 However, alert(params['first_name']) actually gives me the first_name input value. 但是, alert(params['first_name'])实际上给了我first_name输入值。

Why isn't the array going through? 为什么阵列不通过?

Can you try this - 你可以试试这个吗?

$(document).ready(function() {
    var params = new Array();
    var inputs = $(":input");

    $.each(inputs, function(key, value) {
        //I guess the problem was that params is array and your id's were strings
        //array's elements are arr[0], arr[1],
        //not like arr[firstname], arr[lastname], ...
        params[value.id] = value.value;  
    });
    alert(params);
});
//moved everything inside $(document).ready

with this - 有了这个 -

<input name="first_name" id="0" value="1" type="text" class="medium"/>
<input name="last_name" id="1" value="2" type="text" class="medium"/>

<!-- Changed id's from string to numbers. -->

Update: 更新:

Also, try this it might help you understand whats going on - 另外,尝试此操作可能有助于您了解发生了什么-

$(document).ready(function() {
    var params = {}; //use object instead of array
    var inputs = $(":input");

    $.each(inputs, function(key, value) {                       
        params[value.id] = value.value;
    });

    for(var prop in params) {
        alert(prop + " = " + params[prop]);
    }
});

Notice: params is an object now not an array. 注意:params现在是一个对象,而不是数组。

With this - 有了这个 -

<input name="first_name" id="firstname" value="Your first name." type="text" class="medium"/>
<input name="last_name" id="lastname" value="Your last name." type="text" class="medium"/>

您不能简单地将变量传递给服务器,您需要将其序列化为name, value对或使用JSON。

I'm slightly unsure what you're trying to accomplish by creating an array in Javascript like this. 我不太确定您要通过像这样在Javascript中创建数组来完成什么。

Your best bet is probably to use the JQuery command serialize then grab the data using $_GET 最好的选择是使用JQuery命令进行序列化,然后使用$ _GET获取数据

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

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