如何将php数组传递给angularjs服务

时间:2016-08-12 15:36:49

标签: php angularjs arrays

我正在尝试在ng-click函数中传递一个php数组,以便在php控制器中使用它。

这是我的代码我将php数组传递给angular函数。

 <button type="button" class="btn btn-success" 
  ng-click="removeItem('<?php echo  htmlspecialchars(json_encode($value['BookingsHotel']));?>')">Cancel Room</button>

这是我的代码,我正在使用angularjs服务访问我发布的数据

$booked_rooms=htmlspecialchars_decode($this->request->data['rooms']);
$booked_rooms=json_decode($this->request->data['rooms']);

一旦我们进行json解码,它就会给出一个空值。

1 个答案:

答案 0 :(得分:2)

因为你正在使用角度。只需使用$ http与PHP后端进行通信即可。

$http({method: 'POST', url: your_url_variable, contentType: 'application/json; charset=utf-8',
        data: {var1:angular_var1, var2:angular_var2},
        headers: { 'Content-Type': 'application/json; charset=utf-8' }
    }).success(function (result) {
        console.log("result", result);
    }).error(function (data, status, headers, config) {
        console.log('ERROR', data, status, headers, config);
    });

在你的php页面中......

if($_SERVER["REQUEST_METHOD"] == "POST") {
        $postdata = file_get_contents("php://input");
        if(!empty($postdata)) {
            $post = json_decode($postdata);

            $var1 = $post->var1;
            $var2 = $post->var2;

            // do some stuff, then echo the response as json back to your app.

            $result = ["success" => true; "message" => "This is a test message"];
            header('Content-Type: application/json');
            echo json_encode($result);
        }
}