angularjs $ http post请求将字符串数据转换为对象

时间:2018-04-29 04:50:24

标签: php angularjs

当我使用AngularJS $ http post将数据发送到PHP文件时,数据类型应该是一个字符串。但是当我尝试通过then函数从PHP文件中获取输出数据(我只是简单地回显$_POST['string'])时,它会以某种方式自动更改为[object Object]类型。

以下是代码:

JS:

$http({
                method:"POST",
                type:"json",
                url:"./forms/crud.php",
                data:{id:cId}
            }).then(function (d) {
                alert(d.config.data.id);
                console.log(d);
            })

PHP:

if(is_post_quest()){
    echo $_POST['id'];
}

控制台输出:

    {data: "", status: 200, headers: ƒ, config: {…}, statusText: "OK", …}

我可以访问id数据的方法是键入d.config.data.id,这不是我想要的。

enter image description here

我认为问题是从PHP文件中获取AngularJs的数据与使用AJAX的数据有所不同。

对于AJAX,geting数据只需要使用$_POST['id']。 但是,对于AngularJS HTTP POST请求,需要输入类似:

的内容
$data = json_decode(file_get_contents("php://input"));

echo $data->id;

以下是现在的样子。

{data: "568", status: 200, headers: ƒ, config: {…}, statusText: "OK", …}

2 个答案:

答案 0 :(得分:0)

你应该这样做

$http({
                method:"POST",
                type:"json",
                url:"./forms/crud.php",
                data:JSON.stringify({id:cId})
            }).then(function (d) {
                alert(d.config.data.id);
                console.log(d);
            })

答案 1 :(得分:0)

我将做一个例子,用于从角度请求数据并进入PHP代码,然后获得结果。

//角度代码

    var url   = 'your url';
    var data  = {
          "type": "json",
    };

    //Ajax call
    $http.post(url, data).success(function (data, status, headers, config) {

             var result = angular.fromJson(data);
    }).error(function (data, status, headers, config) {

            $scope.preloader=false;

    });

// PHP代码

$ postdata = file_get_contents(" php:// input");

$ request = json_decode($ postdata);

echo json_encode([' data' => $ this-> request-> data,' status' => true,' error' =>'']);

相关问题