3

我希望使用 angularjs 将数据发布到 php 文件中。我参考了以下链接: http ://www.cleverweb.nl/javascript/a-simple-search-with-angularjs-and-php/

我尝试了链接中给出的相同示例,但数据以 JSON 格式发布。我想要 $_POST 变量中的数据。我怎么做?这是我的代码:

搜索.js

   function SearchCtrl($scope, $http) {
        $scope.url = 'php/search.php'; // The url of our search
        // The function that will be executed on button click (ng-click="search()")
        $scope.search = function() {
            // Create the http post request
            // the data holds the keywords
            // The request is a JSON request.  i want the data in $_POST
            $http.post($scope.url, { "data" : $scope.keywords}).
            success(function(data, status) {
                $scope.status = status;
                $scope.data = data;
                $scope.result = data; // Show result from server in our <pre></pre> element
            }).
            error(function(data, status) {
                $scope.data = data || "Request failed";
                $scope.status = status;         
            });
        };
}

搜索.php

   <?php
// The request is a JSON request.
// We must read the input.
// $_POST or $_GET will not work! **but i want it to work!**
    $data = file_get_contents("php://input");
    $objData = json_decode($data);
// perform query or whatever you wish, sample:

include 'connect.php';
mysql_select_db($database,$con);  
$query = 'SELECT * FROM `product`';
$result = mysql_query($query) OR die(mysql_error()); 
$cnt = 0;
while ($row = mysql_fetch_assoc($result)) { 
    $nm = $row['name'];
    //print_r($nm.' ');
    if($objData->data == $nm) {

        $cnt++;
    }
}

if($cnt == 0) {
    echo ' Sorry, no match!';
}
else {
    echo ' I have found what you\'re looking for!';
}

我该如何解决?

4

2 回答 2

2

只是普通的PHP:

$_POST['title'] or $_POST['content'];

你能行的 ;-)

这是对下面帖子下方评论的回答。

于 2014-03-11T11:28:52.473 回答
1

在这里,您可以像往常一样访问 php 文件中的变量。

$http.post("yourpagehandler.php", {
    // Values you with to send to php page
    "title": $scope.title,
    "content": $scope.content
}).success(function(data, status) {
    // Values returned from php handler will be in data

}).error(function(data, status) {
    $scope.data = data || "Request failed";
    $scope.status = status; 
});    
于 2013-04-24T01:41:05.820 回答