繁体   English   中英

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

[英]AngularJS - how can I send data to the php page with $http.post?

我不明白为什么数据对象似乎在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);
}

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);
}

在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM