2017-06-15 64 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 
    } 
相關問題