我一直在使用我的本地服務器(XAMPP)上的Angular的$ http服務發送和請求來自PHP文件的數據,但最近遇到多個問題,當我開始在我的Web服務器,公開託管。第一個問題是,$ http.post不停地給我這個錯誤:AngularJS Post請求不捕捉JSON數據從PHP返回
找不到www.websitepath.com/Object%20Object
顯然不是我輸入的網址。我通過使用$ http服務並僅指定其POST類型來解決此問題。我知道腳本正在連接(如AngularJS腳本到達PHP腳本)並且PHP腳本工作得很好(我自己加載並得到了我想要的字符串)。然而,AngularJS一直給我這樣的:
對象{數據: 「」 狀態:200頭:功能配置:對象,狀態文本: 「OK」}
的數據似乎是儘管空PHP腳本正在打印出一個JSON字符串。我AngularJS腳本和PHP腳本的代碼如下:
var promise = $http({
method: "post",
url: fetchTable,
data: {
choice: 2
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
promise.then(function(response) {
$scope.Units = response.data;
$scope.errorMessage = 'Success!';
console.log($scope.Units);
console.log(response);
},function(error) {
$scope.errorMessage = 'There was a problem fetching information';
});
}]);
這是PHP腳本,我用它來獲取我的數據:
$request = file_get_contents('php://input');
$data = json_decode($request);
$choice = $data->choicePara;
$query = "SELECT unit_id, unitname, unitlink, unitimg, hp, atk, def, rec, upvotes, downvotes, ranking, tier FROM vote_float_v4 ORDER BY ranking ASC";
$result = mysqli_query($dbc, $query);
if (!$query) {
http_response_code(400);
die();
}
else {
$units_array = array();
while ($unit_row = mysqli_fetch_array($result)) {
$unit = new Unit($unit_row); //Create a new unit object based on the information from MySQL
array_push($units_array, $unit);
}
print_r(json_encode($units_array));
}
的PHP正好打印什麼,我想和AngularJS腳本沒有指出任何錯誤,它找不到PHP腳本。實際上,在我的PHP語法出現錯誤之前,AngularJS將警告消息返回給我。但由於某些原因,我不斷收到這個奇怪的JSON對象回來爲我的迴應:
對象{數據: 「」 狀態:200頭:功能配置:對象,狀態文本: 「OK」}
爲什麼數據是空的?!?!我如何讓AngularJS獲取JSON數據?我回來的方式有問題嗎?從評論
**編輯,錯誤,請參閱下面**我沒有角度的專家,但文檔說你應該使用承諾的'.success'回調https://docs.angularjs.org/api/ng/service/$ http(不是'.then') – Plato
nvm我看到關於像你一樣調用它的說明。我唯一的猜測是你沒有在PHP中設置「Content-Type:application/json」標題? – Plato
或可能的PHP輸出實際上並沒有使它對http響應。你可以顯示服務器端代碼,你如何調用PHP的URL? – Plato