【问题标题】:angularjs http.post() not receiving responseangularjs http.post() 没有收到响应
【发布时间】:2017-09-20 06:06:05
【问题描述】:
    <!DOCTYPE html>
<html>
<head>
    <title>login</title>
    <script src="angular.min.js"></script>
    <style type="text/css">
        #a{
            display: none;
        }
    </style>
</head>
<body>


<div ng-app="myapp" ng-controller="myctrl">

<p>Input something in the input box:</p>
<input type="text" ng-model="username" placeholder="username"><br>
<input type="password" name="password" ng-model="password" placeholder="password"><br>
<button ng-click="login()">login</button>
<p id="a">
{{ resmsg }}<br>
<br></p>


</div>
<script type="text/javascript">
    var app= angular.module('myapp',[]);
    app.controller('myctrl', function ($scope , $http, $templateCache) {
        $scope.resmsg ="";

        $scope.login = function()
        {
            $http({
            method: 'POST', 
            url:'http://localhost/ng/myphp.php',
             data:{username : $scope.username, password : $scope.password},
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},  
            cache: $templateCache
        }).success(function(response) {
            $scope.resmsg = response;
        }).error(function(response){

        })
            $scope.resmsg = response;
        }


    })
</script>
</body>

</html>`


myphp.php

<? php

 $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);
    $username = $request->username;
    $password = $request->password;
    if($username == "admin" && $password== "admin"){
        echo "1";
    }
    else {
        echo "0";
    }

?>

我正在尝试使用 angularjs 创建一个简单的登录表单,我有 php 尝试使用 http.post() 方法将我的表单数据发送到 php 文件
在 Angular js 中,但没有得到任何响应并得到 errormsg (screenshot) ,错误就像没有函数一样 成功 帮我摆脱这个错误

【问题讨论】:

    标签: javascript php html angularjs


    【解决方案1】:

    您使用的是哪个版本的 Angular? $http.success 在 Angular 1.5 中已弃用,并在 Angular 1.6 中删除。你应该使用$http.then,像这样:

    $http({
        method: 'POST', 
        url:'http://localhost/ng/myphp.php',
        data:{username : $scope.username, password : $scope.password},
        cache: $templateCache
    }).then(function(response) {
        $scope.resmsg = response.data;
    }).catch(function(response){
        var err = response.data;
        // process error
    })
    

    接下来,你在开始的php标签中有一个错误,有一个额外的空格(使用&lt;?php而不是&lt;? php

    此外,您的服务器似乎没有使用 PHP 处理文件,它只是返回 PHP 代码本身。尝试直接访问脚本,看看它是否返回代码或执行它。如果它以字符串形式返回代码,则您的 Web 服务器配置中存在错误。

    【讨论】:

    • 请看一下错误提示的截图,它将帮助您准确了解我所面临的问题
    • 你说得对,我忘记了内容类型。当您省略该行时,它应该可以正常工作(因此将使用默认内容类型,在 POST 请求的情况下为 application/json)。
    猜你喜欢
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 2015-05-15
    • 2014-05-02
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多