【问题标题】:Passing data from Angularjs to PHP将数据从 Angularjs 传递到 PHP
【发布时间】:2019-10-05 10:39:44
【问题描述】:

我对 Angular 真的很陌生。我正在尝试将变量传递给 php,但响应是“注意:尝试获取非对象的属性”并且数组为 null。

js文件:

var myData = {
            fruit1: 'apple',
            fruit2: 'banana'
        };


$http({
    url: "test.php",
        method: "POST",
        headers : { 'Content-Type': 'application/json' },
        data: myData
    }).success(function(data, status, headers, config) {
        $scope.data = data;
    }).error(function(data, status, headers, config) {
        $scope.status = status;
});

php 文件:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$data = $request->myData;

var_dump($data);

【问题讨论】:

标签: javascript php angularjs


【解决方案1】:

AngularJS 框架中的.success.error 方法have been removed。相反,使用.then.catch 方法:

var myData = {
    fruit1: 'apple',
    fruit2: 'banana'
};

$http({
    url: "test.php",
    method: "POST",
    ̶h̶e̶a̶d̶e̶r̶s̶ ̶:̶ ̶{̶ ̶'̶C̶o̶n̶t̶e̶n̶t̶-̶T̶y̶p̶e̶'̶:̶ ̶'̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶/̶j̶s̶o̶n̶'̶ ̶}̶,̶
    data: myData
}).then(function(response) {
    $scope.data = response.data;
    return response.data;
}).catch(function(err) {
    $scope.status = err.status;
    throw err;
});

$http 服务自动对数据进行 JSON 编码,并自动将内容类型设置为 application/json

在这种情况下,代码不使用.then.catch 方法返回的承诺。如果使用了 Promise,那么在成功和拒绝处理程序中包含 returnthrow 语句很重要。

php 文件:

$postJSON = file_get_contents("php://input");
$dataArr = json_decode($postJSON, TRUE);

var_dump($dataArr);

JSON 编码数据位于 POST 请求的正文中。不发送变量名,只发送内容。

json_decode 函数的第二个参数,指定将对象转换为关联数组。

请记住,这些 POST 请求受same-origin policy 约束。 XHR 请求必须来自与接收 POST 请求的页面具有相同来源的网站页面。

【讨论】:

    猜你喜欢
    • 2014-10-27
    • 1970-01-01
    • 2016-04-28
    • 2017-09-29
    • 1970-01-01
    • 2020-12-12
    • 2010-11-01
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多