You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JSON数组从JavaScript传递到PHP?遇数组键未定义错误

问题排查:AJAX传递JSON数组到PHP出现“数组键未定义”错误

问题描述

我有一个JSON文件,尝试通过jQuery AJAX读取其中的数组到JavaScript变量name_array,再通过请求传递给search_name.php。但在PHP中用json_decode解析后访问数组元素时,出现“数组键未定义”错误,不过传递普通JS数组没有这个问题。

JSON文件内容

{
    "name" : [
        "Alsa", "Alice", "Alas", "Alpha", "Beta", "Bervis", "Bankai", "Celcia", "Celsa", "Ceasar", 
        "Domino", "Dorito", "David", "Eurius", "Easter", "Ethium", "Fourin", "Flora", "Fifa", "Genius"
    ]
}

原代码

原jQuery AJAX代码

function method1(){
    $.ajax({
        url: "name_suggestion.json",
        type: "GET",
        dataType : "JSON",
        success : function(data){
            for(i in data.name){
                name_array.push(data.name[i]);
            }
        }
    });
}
function method2(){
    $.post('search_name.php', {
          names: JSON.stringify(name_array)
        }, function(data, status){
            console.log(data);
        }
    );
}
$.when(method1()).then(method2);

原PHP代码

<?php
$nameData = json_decode($_POST['names']);
print_r($nameData[1]);
?>

错误原因

  1. 异步执行顺序问题:method1没有返回AJAX请求的Promise对象,$.when(method1()).then(method2)会直接执行method2,此时name_array还没被AJAX请求的回调填充,传递给PHP的是空值或未定义内容,解析后自然无法找到数组键。
  2. 变量未声明:原代码中name_array没有提前声明,可能导致变量作用域异常,进一步引发值的错误。
  3. 冗余遍历:用for...in遍历数组虽然能实现赋值,但不如直接将data.name赋值给name_array高效,还可能引入意外属性。

修正后的可运行代码

修正后的jQuery AJAX代码

var name_array = [];
function method1() {
    $.ajax({
        url: "name_suggestion.json",
        type: "GET",
        dataType: "JSON",
        success: function(data) {
            name_array = data.name;
            method2(name_array); 
        }
    });
}

function method2(name_array) {
    $.get('search_name.php', {
        names: JSON.stringify(name_array)
    }, function(data, status) {
        console.log(data);
    });
}
method1();

对应修正后的PHP代码(适配GET请求)

<?php
$nameData = json_decode($_GET['names']);
print_r($nameData[1]);
?>

内容的提问来源于stack exchange,提问作者Nyi Nyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:43:03