开发者

Passing a JavaScript Array to A PHP Class Via AJAX? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Passing JavaScript Array To PHP Through JQuery $.ajax

Can I pass an array to a php file through JavaScript using AJAX? In my application code JavaScript builds the parameters based on user input, and then an AJAX call is made to a processing script.

For example, if the processing script url was process_this.php the call made from JavaScript would be process_this.php?handler=some_handler&param1=p1&param2=p2&param3=p3

Could I do something like this?:

p开发者_开发技巧rocess_this.php?handler=some_handler&param1=[array]

Thanks.


using JQUERY you could do something like this

<script language="javascript" type="text/javascript">
$(document).ready(function() {

    var jsarr = new Array('param1', 'param2', 'param3');

    $.post("process_this.php", { params: jsarr}, function(data) {
        alert(data);
    });

});
</script>

php script

<?php print_r($_POST['params']); ?>

output would be

Array ( [0] => param1 [1] => param2 [2] => param3 )


What about sending an JSON Object via Post to your PHP-Script? Have a look at this PHP JSON Functions


You can use JSON to encode the array to a string, send the string via HTTP request to PHP, and decode it there. You can do it also with objects.

In Javascript you do:

var my_array = [p1, p2, p3]; 
var my_object = {"param1": p1, "param2": p2, "param3": p3};
var json_array = JSON.stringify(my_array);    
var json_object = JSON.stringify(my_object);    
var URL = "process_this.php?handler=some_handler" +
          "&my_array=" + json_array + "&my_object=" + json_object; 

In PHP you do:

$my_array = json_decode($_POST['my_array'])); 
$my_object = json_decode($_POST['my_object'])); 


You can send a json object to your php , thats the standard approach

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜