Ajax PHP 中的未定义值

Ajax undefined value in PHP

当我调用该函数时,我总是得到一个未定义的值,我不明白什么会破坏它。

You are logged in as undefined, Error undefined

Ajax 脚本:

function Submit() {
   console.log('asd')

   $.ajax({
       url: "Server.php",
       type: "POST",
       dataType: "json",
       data: {
          name: "Test2",
          email: "Test@gmail.com"
       },
       success: function(data, textStatus, jqXHR) {
          console.log("You are logged in as: ", data.name);
          $('#user').html("You are logged in as: " + data.name);
       },
       error: function(request, error, data) {
          console.log(arguments);
          alert(" Can't do because: " + error + " DATA: " + data);
       }
   })
}

PHP 脚本:

<?php
header("Content-type: application/json; charset=utf-8");

$errors = [];
$data = [];

if (empty($_POST['name'])) {
    $errors['name'] = 'Name is required.';
}

if (empty($_POST['email'])) {
    $errors['email'] = 'Email is required.';
}

if (!empty($errors)) {
    $data['success'] = false;
    $data['errors'] = $errors;
} else {
    $data['success'] = true;
    $data['message'] = 'Success!';
    $data['name'] = $_POST['name'];
}
echo json_encode($data);
?>

我尝试了所有解决方案都是徒劳的,所以我仍然得到一个不确定的值。我慢慢开始觉得剧本没什么问题了。

您想使用 data.name 但您从未使用 return 名称。因此未定义。 我在下面的示例中添加了 data.name,它似乎工作正常。

<?php
header("Content-type: text/html; charset=utf-8");

$errors = [];
$data = [];

if (empty($_POST['name'])) {
    $errors['name'] = 'Name is required.';
}

if (empty($_POST['email'])) {
    $errors['email'] = 'Email is required.';
}

if (!empty($errors)) {
    $data['success'] = false;
    $data['errors'] = $errors;
} else {
    $data['success'] = true;
    $data['message'] = 'Success!';
    $data['name'] = $_POST['name'];
}

echo json_encode($data);
?>

此外,succes 函数中使用的参数顺序与您使用的顺序不同,在您的情况下,request 将包含您的数据

回调参数不是

success:function(request, data, error)

但是

success: function(data, textStatus, jqXHR)

data.name当然是undefined因为是string

和你的Server.phpreturn这个

{"success":true,"message":"Success!"}

没有data.name但是data.successdata.message

所以你必须写

if (!empty($errors)) {
    $data['success'] = false;
    $data['errors'] = $errors;
} else {
    $data['success'] = true;
    $data['message'] = 'Success!';
    $data['name'] = $_POST['name']; // add this
}