AngularJS - 如何使用$ http.post将数据发送到php页面?

时间:2014-03-31 18:41:34

标签: javascript php ajax angularjs

我无法理解为什么数据对象似乎不存在于php服务器端页面。

$http.post("serverside.php", {"data1":"okpass"}).success(function(data, status, header, config){
                console.log(data);// 
                console.log(status);//202 
                console.log(header);//function (c){a||(a=nc(b));return c?a[O(c)]||null:a}
    });

PHP

if( isset($_POST["data1"]) && $_POST["data1"] == "okpass" ){
    echo "It works!";
    exit(0);
}

2 个答案:

答案 0 :(得分:1)

Angulars http.post不发送表单数据,所以你不能依赖phps $ _POST。它发送json数据。您可以像这样获取数据:

$request = json_decode(file_get_contents("php://input"), true);
if( isset($request["data1"]) && $request["data1"] == "okpass" ){
    echo "It works!";
    exit(0);
}

答案 1 :(得分:0)

在PHP代码中,将JSON转换为旧的$ _POST,如下所示:

//handles JSON posted arguments and stuffs them into $_POST
//angular's $http makes JSON posts (not normal "form encoded")
$content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
if ($content_type_args[0] == 'application/json')
  $_POST = json_decode(file_get_contents('php://input'),true);

//now continue to reference $_POST vars as usual