【问题标题】:Jquery pass multiple arrays to PHPJquery将多个数组传递给PHP
【发布时间】:2017-09-06 18:28:16
【问题描述】:

我正在尝试使用 AJAX 将 4 个 js 数组发送到一个 php 页面,一旦我希望它们在 4 个 php 数组中用于 php 脚本。

使用 $.type(var) 我已经确认我的 js 数组实际上是数组。

使用以下方法发送一个数组:

        $.ajax({
            type: "POST", 
            cache: false,
            url: "test.php",    
            data : arrayA: arrayA,
            success: function(res) {
                console.log (res)
            }
        });

但以下失败:

var data = { arrayA: arrayA, arrayB: arrayB, arrayC: arrayC, arrayD: arrayD }

            $.ajax({
                type: "POST", 
                cache: false,
                url: "test.php",    
                data : data,
                success: function(res) {
                    console.log (res)
                }
            });

我的php页面是:

$arrayA = $_REQUEST['arrayA'];
$arrayB = $_REQUEST['arrayB'];
$arrayC = $_REQUEST['arrayC'];
$arrayD = $_REQUEST['arrayD'];

我确定我错过了明显的,请有人建议。

谢谢

【问题讨论】:

  • 错误是什么?
  • 可以尝试将所有这些数组放入 JS 中的一个数组中,然后将该数组传递给 php,我在此实例中使用 $_POST['array'];
  • 感谢您的回复。没有显示错误,似乎什么也没发生。如何将它组合成一个数组,然后在 PHP 中将其拆分回来?

标签: php jquery arrays ajax


【解决方案1】:

试试这个,这个方法应该可以的:

// Create the arrays you want
var arrayA = ["cat","dog"];  
var arrayB = ["lamp","rock"];

// Combine the arrays into one
var array = [arrayA, arrayB];


 // Send them via ajax
 $.ajax({
            type: "POST", 
            cache: false,
            url: "test.php",    
            data : array: array,
            success: function(res) {
                console.log (res)
            }
        });

PHP端:

<?php
 // (use print_r($_POST) to see what comes through and how it is setup in the POST array, that way you can get the keys and names and build it out how you wish
  foreach($_POST['array'] as $array){
      // This will give each array, you could also get the array keys and use those as names if you wish
  }

?>

【讨论】:

  • 谢谢,我会试一试。一旦它在 PHP 中,我如何将它返回到单个数组?
  • 它将作为这些数组的一个数组出现,使用 foreach($_POST as $array) 然后创建动态命名的数组或您将要创建的数组
  • 谢谢,我会尽快试试这个
  • 谢谢,我已经在我的 php 中使用 json stringify 和 json_decode 完成了这项工作
猜你喜欢
  • 2011-07-09
  • 1970-01-01
  • 2015-01-16
  • 2018-07-25
  • 2015-08-21
  • 1970-01-01
  • 2012-06-01
  • 1970-01-01
  • 2015-08-07
相关资源
最近更新 更多