首页 > 解决方案 > 如何通过jquery将两个js数组传递给PHP

问题描述

我正在尝试将两个 js 数组传递给 jquery ajax 到 php 后端。但是在网络选项卡中,在我收到的开发工具中 > 无法加载响应数据。任何建议 TY

var arr1 = [];
var arr2 = [];
var id = 2432;

$.ajax({
       type: "POST",
        url: '/api/put/update_dealer_manufacturer.php',
        async: true,
        data: {arr1, arr2, id},
        dataType: 'json',
        success: function(data) {
           let output = data;
        },
        error: function(data) {
          console.log("error");
          console.log(data);
        }
     });

在后端我正在做:

$output = array(
  "success" => false,
  "msg" => ''
);

$arr1 = $_REQUEST['arr1'];
$arr2 = $_REQUEST['arr2'];
$id = $_REQUEST['id'];

在后端我有

<?php

if(empty($_REQUEST['id'])){
   $output['msg'] = "Authentication error";
   echo json_encode($output);
   die();
}

$new_manufacture = $_REQUEST['arr1'];
$delete = $_REQUEST['arr2'];
$id = addslashes($_REQUEST['id']);

foreach然后我在每个 arr 上循环。在后端文件的末尾,我这样做了,但由于某种原因,我没有得到任何结果来判断我是否到达了后端文件。

$output['success'] = true;
echo json_encode($output);

标签: javascriptphpjquery

解决方案


我无法发表评论(因为代表不允许这样做。)尝试更改以下内容以查看它是否允许您继续。

data: {"arr1":arr1, "arr2":arr2, "id":id},
dataType: 'html',

我通过执行console.log 测试成功和失败......这就是我得到的......

Array
(
    [0] => 123
    [1] => 234
)
Array
(
    [0] => 345
    [1] => 456
)
2432

完整代码:

<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script type="text/javascript">
var arr1 = ['123','234'];
var arr2 = ['345','456'];
var id = 2432;

$.ajax({
       type: "POST",
        url: 'code2.php',
        async: true,
        data: {"arr1":arr1, "arr2":arr2, "id":id},
        dataType: 'html',
        success: function(data) {
           console.log(data);
        },
        error: function(data) {
          console.log("error");
          console.log(data);
        }
     });

</script>

推荐阅读