Angularjs $ http发布请求数据和未定义错误的响应

时间:2016-10-10 07:15:28

标签: javascript php mysql angularjs http-post

我想从服务器端获取特定值。因此我使用$ 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];

?>

1 个答案:

答案 0 :(得分:2)

问题可能出在你的$ 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 function。
  • config - {Object} - 用于生成请求的配置对象。

因此,请尝试更改您的内容类型&#39;到&#39; application / json&#39;,因为那是你在http请求体中发送的内容。如果它不起作用,请将标题更改为config以进行测试。

如果它也不起作用,我会使用任何工具,例如邮递员&#39;检查API,并确保它正常工作,并尝试调试PHP代码(我无法帮助您完成此部分)