PHP/jQuery AJAX JSON error

PHP/jQuery AJAX JSON error

本文关键字:JSON error AJAX jQuery PHP      更新时间:2023-09-26

当我试图使用jQuery Ajax从PHP页面接收代码时,我发现了一个奇怪的错误:"未定义变量:errors"

<?php
$errors = array("already_signed" => "You are already signed in", "field_empty" => "All fields must be filled", "long_username" => "Username length must be less then 40 symbols", "incorrect_email" => "Your mail is incorrent", "user_exists" => "User with such username already exists", "account_not_found" => "Account not found", "passwords_arent_same" => "Passwords must be the same");
Function check_post() {
    $answer = array("ok" => "false", "answerswer" => $errors["field_empty"]);
    echo json_encode($answer);
}
check_post();
?>

如果我将echo不带函数-一切都会好的。感谢您的帮助

您似乎在那里至少缺少一个}。实际上,您的函数定义没有关闭,因此它读起来像一个无限递归调用。

同样,您已经在函数之外定义了$errors。PHP不允许"较低"代码作用域看到在较高作用域定义的变量。您需要将$errors声明为函数中的全局变量:

<?php
$errors = array(....);
function check_post() {
   global $errors;
   $answer = ...
   ...
}
check_post();

您正在尝试从函数内部访问全局变量。为了实现这一点,您需要使用"global"关键字:

<?php
$errors = array("already_signed" => "You are already signed in", "field_empty" => "All fields must be filled", "long_username" => "Username length must be less then 40 symbols", "incorrect_email" => "Your mail is incorrent", "user_exists" => "User with such username already exists", "account_not_found" => "Account not found", "passwords_arent_same" => "Passwords must be the same");
function check_post() {
    global $errors;
    $answer = array("ok" => "false", "answerswer" => $errors["field_empty"]);
    echo json_encode($answer);
}
check_post();
?>