api:
<?php
session_start();
error_reporting(0);
include("includes/config.php");
$data = array();
$query = "SELECT product_name FROM inventory group by product_name;";
$query .= "SELECT name FROM brands;";
$query .= "SELECT name FROM categories;";
mysqli_multi_query($con,$query);
$result = mysqli_store_result($con);
while($row = mysqli_fetch_assoc($result))
{
$data[] = array(
'products' => $row['product_name']
);
}
mysqli_free_result($result);
mysqli_next_result($con);
$result = mysqli_store_result($con);
while ($row = mysqli_fetch_assoc($result)) {
$data[] = array(
'products' => $row['name']
);
}
mysqli_free_result($result);
mysqli_next_result($con);
$result = mysqli_store_result($con);
while ($row = mysqli_fetch_assoc($result)) {
$data[] = array(
'products' => $row['name']
);
}
mysqli_free_result($result);
mysqli_close($con);
$results = json_encode($data);
//$json = json_decode($results, true);
print($results);
?>
.js文件
$.ajax({
type:"GET",
url:"http://localhost/leafteaculture/autocomplete-api.php",
datatype:"JSON",
success:function(json){
alert(json);
/*for(var i=0;i<json.length;i++){
var countries = json[i].products;
alert(countries);
}*/
}
});
我正在更新我的问题。现在,当我点击url并成功后,我会使用Alert检查我的api数据及其完美运行情况。现在,我的数据如下所示:
[{"products":"Twinings"},{"products":"Lipton"},{"products":"Dilmah"},{"products":"Fassai"}]
如果我在var countries
中获得了数据,则它必须看起来像这样:
["Twinings","Lipton","Dilmah","Fassai"]
那么,我该怎么做?请帮助我。
谢谢
答案 0 :(得分:0)
在您的php文件中,而不是
$data[] = array('products' => $row['name'])
尝试以下操作:
$data['products'][] = $row['name']
这将导致JSON的格式如下:
{"products": ["Red Label Natural Care", ...]}
然后您可以通过
以JS代码访问数组json.products
答案 1 :(得分:0)
您可以使用map函数返回每个产品值。
var products = [{"products":"Twinings"},{"products":"Lipton"},{"products":"Dilmah"},{"products":"Fassai"}];
console.log(products.map(function(item) {
return item[Object.keys(item)[0]];
}))
我在这里使用Object.keys
来获取每个产品的第一把钥匙,您也可以直接使用products
(代替return item["products"]
)
$(document).ready(function() {
var products = [{"products":"Twinings"},{"products":"Lipton"},{"products":"Dilmah"},{"products":"Fassai"}];
console.log(products.map(function(item) {
return item[Object.keys(item)[0]];
}))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>