我正在尝试将JavaScript字符串数组(arrayItems
)发送到PHP Web服务,以便将查询发送到MySQL数据库。但是,Web服务不返回任何数据。仅当JavaScript字符串数组只有1个项目时,才能从Web服务正确返回数据。
Web服务使用PHP 5.6.30。
显示返回数据的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;
});
};
将请求发送到Web服务的app.js示例:
.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 :(得分: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
}