我有一个数据库表,其字段包含位置的纬度和经度坐标。我想使用数据库中的信息为Google Map视图创建标记。
我已将查询功能强制为
function getCords(){
$link = connectDB();
$query = "SELECT * FROM tour";
$results = mysqli_query($link, $query);
$jsonArray = array();
while ($row = mysqli_fetch_assoc($results)){
$jsonArray[] = array('fileName' => $row['FileName'], 'lat' => $row['Lat'], 'lon' => $row['Lon']);
}
return json_encode($jsonArray);
}
当我从php页面调用此函数时,它返回通常的JSON格式。
我的问题是执行ajax查询。我在上面的php脚本文件中有查询功能,该文件包含六个左右的实用程序函数,用于控制登录,注销,注册等。为了通过jquery查询数据库,我尝试了
var request = $.ajax({
type:"GET",
url: "includes/phpscripts.php?action=cords",
type: "json"
});
var response = request.responseText;
我的问题是响应总是空的。这是由于URL的形成还是出于其他原因?
答案 0 :(得分:7)
$.ajax({
type:"GET",
url: "includes/phpscripts.php?action=cords",
dataType: 'json', // necessary, because you're sending json from server
success: function(response) { // response will catch within success function
console.log(response);
}
});
或
var request = $.ajax({
type:"GET",
url: "includes/phpscripts.php?action=cords",
dataType: 'json', // necessary, because you're sending json from server
}).done(function(response) {
console.log(response);
});
而不是return json_encode($jsonArray);
,请使用echo json_encode($jsonArray);
答案 1 :(得分:0)
请参阅jQuery.ajax,您没有使用正确的格式,这就是响应为空的原因。
成功处理程序将从服务器端返回响应。所以请使用它:
$.ajax({
type:"GET",
url: "includes/phpscripts.php?action=cords",
type: "json"
success : function(response){
console.log(response);
}
});
答案 2 :(得分:0)
响应为空,因为执行该行代码时未从服务器返回响应。尝试在ajax回调中设置responseText。见下文,
var response = '';
var request = $.ajax({
type:"GET",
url: "includes/phpscripts.php?action=cords",
type: "json"
}).done (function (data) {
console.log(data); //json object as jquery converts it for you
console.log(request.responseText); //string text as returned the server.
response = request.responseText;
//^-- response is a string text as returned the server.
});