簡體   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