简体   繁体   中英

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. 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:

<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. However, alert(params['first_name']) actually gives me the first_name input value.

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.

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.

Your best bet is probably to use the JQuery command serialize then grab the data using $_GET

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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