我正在尝试在JSON对象数组中转换我的邮政编码和城镇,但我想我做得不对,我需要它来实现自动完成功能。
这是我的代码:
var request_image = function(url) {
return new Promise(function(resolve, reject) {
var img = new Image();
img.onload = function() { resolve(console.log("sdfsdf")); };
img.onerror = function() { reject(console.log("wwwwwwww")); };
var imageSource = url + '?random-no-cache=' + Math.floor((1 + Math.random()) * 0x10000).toString(16);
$(img).on("load",loadHandler).on("error",errorHandler)[0].src = imageSource;
console.log(img.src)
});
};
var ping = function(url, multiplier) {
return new Promise(function(resolve, reject) {
var start = (new Date()).getTime();
var response = function() {
var delta = ((new Date()).getTime() - start);
delta *= (multiplier || 1);
resolve(delta);
};
var errorResponse = function() {
var delta = "Could not connect"
reject(delta);
};
request_image(url).then(response).catch(errorResponse);
// Set a timeout for max-pings, 5s.
setTimeout(function() { reject(Error('Timeout')); }, 5000);
});
};
var errorHandler = function(event) {
sleep(3000);
console.log("errorHandler");
console.log(event);
};
var loadHandler = function(event) {
sleep(3000);
console.log("loadHandler");
this.appendTo("#imgHolder");
};
var sleep = function(milliseconds) {
var start = new Date().getTime();
while(1) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
};
答案 0 :(得分:0)
您需要将对象中的每个条目都设为一个数组。这应该有效:
while($row=mysqli_fetch_array($result)){
$matches[] = array(
'label'=> $row["postcode"],
'value'=> $row["town"],
);
}
答案 1 :(得分:0)
请勿尝试使用字符串插入json。你可以完全依赖json_encode。
我会这样做
$sql = "SELECT * FROM uk_postcodes";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = array(
"label" => $row['postcode'],
"value" => $row['town']
);
}
header('Content-Type: application/json');
echo json_encode($dname_list);