我想从服务器端获得特定的值。因此,我使用$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);
});
如果我没有错,你可以使用两者,头或配置,但似乎你没有正确使用属性头,文档说:
- headers - {function([headerName])} - Header getter函数。
- config - {Object} -用来生成请求的配置对象。
所以试着把你的'Content-Type'改成'application/json',因为那是你在http请求体中发送的内容。如果不工作,将headers改为config到test.
如果它也不工作,我会使用任何工具,如'postman'来检查API,并确保它是工作的,并尝试调试PHP代码(我不能帮助你与这部分)