开发者

jquery post method to send javascript array to php doesn't work for me, why?

I was looking over the web how to send Java script array, like this one:

var array = ["thing1", "thing2", "thing3"];"

To php file on my server.

Then I came across jQuery .post() method, but when I use it my php file remains empty!

The code I was using is:

var array = ["thing1", "thing2", "thing3"];
$(document).ready(function() {
    $.post( 'hs.php', array, function(data, statusText) {
        alert("Uploaded")
    });
})

But I have no much experience with php and I don't 开发者_StackOverflow中文版know should php be empty or have some code to retrieve array! All I want is to store javascript array on server file so I can read that array again on page load.

What am I doing wrong?

Can someone show short example of working html and php code?


You can use JSON for this. JSON encode the javascript array and send it to your php and decode the json-decoded array on server side.

JSON is a standard notation which converts objects (arrays, class objects etc) to string notation, which can be passed via http.

POST variables are stored in data option of jQuery post/ajax. Now lets say you want to pass following array to php:

var my_array = ["my", "name", "is", "foo", "bar"];

You can then json encode it using jQuery's JSON encoding plugin.

var my_json_val = $.JSON.encode(my_array);

Then you can pass this value to server using:

$.post({
url: 'my_url',
data: { my_json_name: my_json_val}
});

At server side you can do this:

$my_json_encoded = $_POST['my_json_name'];
$my_json_val = json_decode($my_json_encoded);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜