使用angular.js将数据发送到php文件

时间:2016-04-26 21:38:17

标签: javascript php angularjs http

对,所以我有一个使用http方法将数据发送到php文件的角度函数。我希望处理数据并将其回显到页面上以确认php文件已处理它的php代码。我目前正在收到未定义警报回复给我,当然我应该收到电子邮件的回复给我?谢谢大家

我遵循本教程https://codeforgeek.com/2014/07/angular-post-request-php/

var request = $http({
 method: "post",
 url: "functions.php",
 data: {
    email: $scope.email,
    pass: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

//.then occurs once post request has happened
//success callback
request.success(function (response) {
  alert(response.data);
},

//error callback
function errorCallback(response) {
  // $scope.message = "Sorry, something went wrong";
  alert('error');
});

我的PHP代码......

//receive data from AJAX request and decode
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

@$email = $request->email;
@$pass = $request->pass;

echo $email; //this will go back under "data" of angular call.

1 个答案:

答案 0 :(得分:1)

来自documentation

已弃用$http旧版承诺方法successerror。请改用标准then方法。如果$httpProvider.useLegacyPromiseExtensions设置为false,则这些方法会抛出$http/legacy错误。

您的代码应如下所示:

request.then(
    function( response ) {
        var data = response.data;
        console.log( data );
    },
    function( response ) {
        alert('error');
    }
);

现在,您需要以JSON格式对来自服务器的响应进行编码,因此将echo $email;替换为:

echo json_encode( array(
    'email' => $email
) );

您可以通过email <从angularjs $http.success promise回调函数(它是then闭包内的第一个函数)访问response.data.email属性/ p>