簡體   English   中英

PHP-從AngularJS $ http.get請求獲取參數

[英]PHP - get params from AngularJS $http.get request

如何使用PHP檢索通過$ http.get請求傳遞的參數?

這是我的控制器:

app.controller('phonesCtrl', function ($scope, $http, $routeParams) {

    $scope.make = $routeParams.make;
    console.log($routeParams); // Console displays 'Object {make: "apple"}'
    console.log($scope.make); // Console displays 'apple'

    $http({
        method: 'POST',
        url: 'tools/get.php',
        params: $routeParams, // Already an object: "{"make" : apple}"
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(function (response) {
        $scope.phones = response.data;
    });
});

我的PHP嘗試:與$ http.post一起使用,但是有什么告訴我我不能使用file_get_contents函數來執行相同操作。

<?php

$data = json_decode(file_get_contents("php://input"));

var_dump($data); // Outputs NULL
var_dump($_POST["make"]); // Outputs NULL
var_dump($_POST); // Outputs empty array

$con = new PDO('mysql:host=localhost;dbname=mydb', 'root', 'root');

$stmt = $con->prepare("SELECT * FROM phones WHERE make = ?");
$stmt->bindParam(1, $make);
$stmt->execute();

$result = json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

print_r($result);

?>

我還使用$routeProvider服務保持鏈接清潔。 起初,我意識到控制台正在輸出空白對象,因此我將配置更改為:

.when('/get/:make', { // Added /:make
    templateUrl: 'tools/get.php',
    controller: 'phonesCtrl'
})

因此,現在當我導航到/ get / apple時,控制台將輸出“ apple”。

在PHP中使用

$_GET["make"]

獲得參數。

如果您在此處閱讀PHP $ _POST文檔,則可以找到

當將application / x-www-form-urlencoded [您正在使用的內容]或multipart / form-data用作請求中的HTTP Content-Type時,通過HTTP POST方法傳遞給當前腳本的變量的關聯數組。

您嘗試做的是傳遞帶有POST參數的GET請求。 您可以像這樣通過www.yoursite.it/page.php?name=Matteo傳遞它,然后使用$name = $_GET['name']接受變量,或者以POST方式傳遞,如下所示:

$http({
method: 'POST', //CHANGE THIS FROM GET TO POST
url: 'tools/get.php',
params: {
    name: 'Matteo' //USE PROPER JAVASRIPT OBJECTS
},
headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
}
})

然后,您將獲得帶有$name = $_POST['name']的變量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM