I am trying to send the JavaScript
array to my php
, but php
gets empty [].
It even shows like that in my browser. I have always sent JSON
and had no problem, but now have this format.
I have this example that makes no sense...it's just a code to illustrate the issue:
var blah = [];
var letters = ['a', 'b', 'c', 'd'];
for (var i = 0; i < letters.length; i++)
{
blah[letters[i]] = i;
}
Inside firebug DOM
it shows as follows:
blah []
a 0
b 1
c 2
d 3
When I do
alert(blah)
------------------------------- I get empty alert(JSON.stringify(blah))
----- I get [] alert(blah.a)
---------------------------- I get 0 So how can I pass this object to php
? Thanks
Instead of an array, try using an object.
So instead of:
var blah = [];
Try
var blah = {};
Arrays are continuously numerically indexed. They do not have strings as key names.
What you want is an object {}
, not an array []
.
I have answered this before. Anyway, blah
is an array, but you are not using it as array, you are using it as a hashmap. Arrays work with indexes and maps work with keys. Any object in JS can also act like a map. For eg
var obj = new Object();
obj.a = 10;
obj["b"] = 20;
var obj2 = function(){...}
obj2.foo = 10;
obj2.bar = "baz";
Similarly, Array
is also and Object
and can act like a map. But when you use the array like a map, its array is not utilized to store the elements. They just act like above. So the length
of an Array is 0 even though it has properties attached to it.
What you must do is use Array methods like push
and pop
to populate and retrieve from it.
Can not assign key value collection in array. You need to work on objects:
var obj = {
key1: value1,
key2: value2
};
for converting array to string you can use:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.toString();
with seperator:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(" and ");
try this:
var blah = {};
var letters = ['a', 'b', 'c', 'd'];
for (var i = 0; i < letters.length; i++)
{
blah[letters[i]] = i;
}
alert(JSON.stringify(blah));
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.