[英]Angularjs $http post request data and response with undefined error
我想從服務器端獲取特定值。 因此,我正在使用$ http將變量從前端(Angularjs javascript)傳遞到后端(php)。 服務器端(php)之后從前端獲取值。 它將運行sql查詢以從mysql獲取數據,並將數據返回到前端。 但是,在我的前端控制台中,它顯示了未定義的錯誤。 以下是我的代碼:
前端Javascript
$http({
method: "post",
url: "http://localhost/php/UpdateLastLogin.php",
data: {
user_name: user_name,
CurrentTimestamp: CurrentTimestamp
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(response) {
console.log(response);
}).error(function(response) {
console.log(response);
});
后端PHP
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('P3P: CP="CAO PSA OUR"');
header("Content-Type: application/json; charset=utf-8");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
@$CurrentTimestamp = $request->CurrentTimestamp;
@$user_name = $request->user_name;
$servername = "localhost";
$username = "jack";
$password = "1234";
$dbname = "daikinchat";
$CurrentTimestamp = '"' . $CurrentTimestamp . '"';
//$user_name = '"' . $user_name . '"';
$user_name = "Lisa Wong";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT last_login_timestamp FROM user_directory WHERE username = '$user_name'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
echo $row[0];
?>
問題可能出在您的$ http呼叫中,我的$ http呼叫看起來像:
$http({
method: 'post',
url:'http://localhost/php/UpdateLastLogin.php',
data: {...},
config: 'Content-Type: application/json;'
}).then(function (response) {
console.log(response);
}, function (response) {
console.log(response);
});
如果我沒記錯的話,您可以同時使用標頭或配置,但是似乎您沒有正確使用屬性標頭,該文檔說:
因此,請嘗試將“ Content-Type”更改為“ application / json”,因為這就是您在http請求正文中發送的內容。 如果不起作用,請將標頭更改為config進行測試。
如果兩者都不起作用,我將使用諸如“郵遞員”之類的任何工具來檢查API,並確保其正常工作,然后嘗試調試PHP代碼(這一部分我無法為您提供幫助)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.