使用Ajax将数组从javascript发布到php函数

Post array from javascript to php function using Ajax

本文关键字:php 函数 javascript Ajax 数组 使用      更新时间:2023-09-26

我想通过ajax将一个数组从java脚本发布到php。但我不知道如何做到这一点,尤其是将它发送到类似控制器类的php函数中。如果我错了,请纠正我,这是我的java脚本源,作为发送数组的函数:

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

我试过了,但还是失败了。真的需要帮助。。

如JQuery API文档中所述,您可以使用

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'
    });

这样尝试,

var data_to_send = $.serialize(array);
$.ajax({
            type: "POST",
            url: 'post.php',
            data: data_to_send,
            success: function(msg){
            }
        });

你可以像下面这样作为json传递,

$.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) {
                                }

你可以试试这个。这将工作

示例

ajax代码:

$.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代码:

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