简体   繁体   中英

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

I can't understand why the data object seems doesn't exist at php server side page.

Angular

$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 does not send form data, so you cant rely on phps $_POST. It sends json data. You can get the data like so:

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

In the PHP code, convert the JSON into good old $_POST like this:

//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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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