如何获得从 PHP 到 AJAX 的响应?

How to get the Response from PHP to AJAX?

要从我的 PHP 服务器接收响应对象,我认为您可以将变量的名称放入 success 函数并对其进行处理。 不幸的是,这不起作用。我的代码有什么问题吗?我正在为 PHP 服务器使用名为 Slim 3 的框架。

这是我的 AJAX 函数:

$.ajax({
    type : "POST",
    url : "http://server/authenticate",
    contentType : "application/json",                                                  
    data: '{"username":"' + username + '", "password":"' + password + '"}',     
    success : function(data) {
        console.log(response)             // response is not defined
        console.log(response.status)      // response is not defined
        console.log("Test")               // Works!
        console.debug(data)               // Nothing, blank line 
        console.debug(data.status)        // undefined       
    }
});

我的PHP函数:

public function authenticate($request, $response)
{             
    ...

    return $response->withStatus(200)->withHeader('Set-Cookie', $token);
    //return $response;

}

一般来说,我的 success 函数可以工作,但我想在其中放置一个 if 来真正检查状态代码是否为 200。但正如我上面所展示的,有未定义的。 如果我通过 F12 检查我的浏览器,我可以看到状态代码被正确传输,例如200

success: function(data) {
    if(data.status == 200) {
        // ...
    }
}

使用 withJson(),您的回复将转换为有效的 json-response,它还会自动为您设置 PHP header。

根据文档,

The Content-Type of the Response is automatically set to application/json;charset=utf-8.

这意味着,只要您传递给 withJson() 的变量是一个数组,该方法应该就是您所需要的——您不必担心设置 headers 或json-encoding 就这样

$data = array(...);
return $response->withJson($data);

一种方法是 return 来自 PHP 数组的 JSON 对象:

$content = ["foo" => 'bar', ...] ; //Any data you wish to return
return $response->withJson($content);