2017-06-15 48 views
0

我试图发送一个JavaScript字符串数组(arrayItems)到PHP Web服务,以便将查询发送到MySQL数据库。尽管如此,没有数据从Web服务返回。当JavaScript String Array只有一个项目时,只能从Web服务正确返回数据。发送的JavaScript字符串数组,PHP Web服务

Web服务是PHP 30年6月5日。

样本HTML来显示返回的数据:

<ul> 
    <li ng-repeat="item in arrayInfo track by $index">ID: {{ item.idFruit }}, 
name: {{ item.name_fruit }}</li> 
</ul> 

Ctrl控制器的样品:

angular.module('myApp').controller('Ctrl', ['$scope', 'services', Ctrl]); 

function Ctrl($scope, services) { 
    var arrayItems = ["apple", "banana", "orange"]; 
    services.getInfo(arrayItems).then(function(data){ 
     $scope.arrayInfo = data.data; 
    }); 
}; 

的app.js的样本来发送请求到Web服务:

.factory('services', ['$http', function($http){ 
    var serviceBase = 'services/'; 
    var obj = {}; 
    obj.getInfo = function (arrayItems) { 
     return $http.get(serviceBase + 'get_info?arrayItems=' + arrayItems); 
    }; 
    // return obj 
    return obj; 
}]); 

样品在PHP Web服务:

private function get_info(){ 
    if($this->get_request_method() != "GET"){ 
     $this->response('', 406); 
    } 
    $arrayItems = (array)$this->_request['arrayItems']; 
    $fruits = implode("','", $arrayItems); 
    $query = "SELECT idFruit, name_fruit FROM Table_Fruits WHERE name_fruit IN 
('$fruits')"; 
    $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__); 
    if($r->num_rows > 0){ 
     $result = array(); 
     while($row = $r->fetch_assoc()){ 
      $result[] = $row; 
     } 
     $this->response($this->json($result), 200); // send user details 
    } 
    $this->response('', 204); // send user detail 
} 

谢谢*

回答

0

同时,我解决我自己的问题。

有解决办法,如果有人需要它的未来:

(问题:JavaScript字符串数组竟被转换为PHP字符串数组在我的问题)

解决方案:

private function get_info(){ 
    if($this->get_request_method() != "GET"){ 
     $this->response('', 406); 
    } 
    $arrayItems = $this->_request['arrayItems']; 

    //Explode on comma 
    $vals = explode(',', $arrayItems); 
    //Trim whitespace 
    foreach($vals as $key => $val) { 
     $vals[$key] = trim($val); 
    } 
    //Return empty array if no items found 
    //http://php.net/manual/en/function.explode.php#114273 
    $arrayItems_php = array_diff($vals, array("")); 

    $fruits = implode("','", $arrayItems_php); 
    $query = "SELECT idFruit, name_fruit FROM Table_Fruits WHERE name_fruit 
    IN ('$fruits')"; 
     $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__); 


    if($r->num_rows > 0){ 
     $result = array(); 
     while($row = $r->fetch_assoc()){ 
     $result[] = $row; 
     } 
     $this->response($this->json($result), 200); // send user details 
    } 
    $this->response('', 204); // send user detail 
    } 
相关问题