[英]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) {
// ...
}
}
一種方法是從PHP數組返回JSON對象:
$content = ["foo" => 'bar', ...] ; //Any data you wish to return
return $response->withJson($content);
使用withJson()
,您的響應將轉換為有效的json-response,並且還會自動為您設置PHP標頭。
從文檔中
響應的Content-Type自動設置為
application/json;charset=utf-8
。
這意味着,只要您傳遞給withJson()
的變量是一個數組,該方法就應該是您所需要的-您不必擔心進一步設置標頭或json編碼,例如
$data = array(...);
return $response->withJson($data);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.