开发者

send array to php from javascript?

i want to send a javascript array to php using jquery ajax.

$.post("controllers/ajaxcalls/users.php",
{
    links: links
});

where the second 'links' is a javascript array.

when i've got this array:

'1' ...
    '1' => "comment1"
    '2' => "link1"
    '3' => "link2"
    '4' => "link3"
'2' ...
    '1' => "comment2"
    '2' => "link4"

then using:

var jsonLinks = JSON.stringify(links);
alert(jsonLinks);

will give me:

[null,[null,"comment1","link1","link2","link3"],[null,"comment2","link4"]]

seems to me that something is wrong. and i cant use json_decode on php side to get开发者_开发问答 the elements.

what function should i use to convert it to json and how do i access it on the php side? have struggled with this in some hours now...would appreciate some help.


You could use json_decode to read the passed json value. Take a look at this post.


I'm not sure if your example will work (did you try it?) If not, you can use json to send your array, and then decode it with php (http://www.php.net/manual/en/function.json-decode.php)

As written on the JSON website: The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.

Values that do not have a representation in JSON (such as functions and undefined) are excluded.

Nonfinite numbers are replaced with null. To substitute other values, you could use a replacer function like this:

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}

Full page can be found here: http://www.json.org/js.html


You can always serialize the array like so:

books: $.param(books)

Which works as follows:

$.param({a: [1, 2]}) // output: "a=1&a=2"


im still fairly new too say maybe this method isnt the most secure, but you can always turn your javascript array into a string and then pass it through the URL for the php to GET.

so:

for(var i=0;i < jsarray.length;i++) 
{
    var x = jsarray[i];
    urlstring += "myvalue[]="+x+"&";
}

 document.location.href = "mypage.php?"+urlstring;

and then the php would be:

$phparray = $_GET['myvalue'];

hope that helps

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜