简体   繁体   中英

Post array from javascript to php function using Ajax

i want to post an array from java script to php by ajax. But i don't know how do that, especially send it to php function like controller class. Correct me if i'm wrong, this is my java script source, as a function to send an array :

<script>
 function send(){
    var obj = JSON.stringify(array);
    window.location.href = "post.php?q=" + obj;
}
</script>

i was try, but still fail. really need help..

As described in the JQuery API documentation , you can use

var rootPath="http://example.com/"
var jsonData = $.toJSON({ q: array });
var urlWS = rootPath + "post.php";
$.ajax({
    url: urlWS,
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: jsonData,
    success: function(result) {
            // do something here with returned result
    }
});
var array= [];
array[0] = 'hi';
array[1] = 'hello';

    $.ajax({
      url: 'http://something.com/post.php',
      data: {array: array},
      type: 'POST'
    });

try like this,

var data_to_send = $.serialize(array);

$.ajax({
            type: "POST",
            url: 'post.php',
            data: data_to_send,
            success: function(msg){

            }
        });

or

you can pass as json like below,

$.ajax({
    type: "POST",
     url: 'post.php',
    dataType: "json",
    data: {result:JSON.stringify(array)},
    success: function(msg){

    }
});
var arr = <?php echo json_encode($postdata); ?>;
ajax: {
                                url:"post.php"    
                                type: "POST",
                                data: {dataarr: arr},
                                complete: function (jqXHR, textStatus) {
                                }

You can try this .this will work

example

ajax code:

$.ajax({
  url: 'save.php',
  data: {data: yourdata},
  type: 'POST',
  dataType: 'json', // you will get return json data
  success:function(result){
   // to do result from php file
  }
});

PHP Code:

$data['something'] = "value";
echo json_encode($data);

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