我最近更新了我的PHP和用於解析我的PHP到Ajax的代碼已停止工作。我改變了我的PHP使用PDO,不得不使用jsoncallback簡單JSON編碼改變我return語句:AJAX解析錯誤
<?php
header('Content-type: application/json');
$con = new PDO('mysql:host=localhost;dbname=db;charset=utf8mb4;''root', 'pass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$sql = "SELECT idlocations, name, latitude, longitude FROM `locations`";
$con->query("SET NAMES utf8");
$result = $con->query($sql);
$records = array();
if($result !== false)
{
$records = $result->fetchAll(PDO::FETCH_ASSOC);
print_r($records);
//$_GET['jsoncallback'] . '(' . json_encode($records) . ');';
echo json_encode($records);
}
else
{
print_r($con->errorInfo());
}
?>
上面的代碼將返回如下:
Array
(
[0] => Array
(
[idlocations] => 1
[name] => BierMarkt
[latitude] => -79.3708
[longitude] => 43.6473
)
[1] => Array
(
[idlocations] => 2
[name] => jacks
[latitude] => -79.4200
[longitude] => 43.6555
)
)
[{"idlocations":"1","name":"BierMarkt","latitude":"-79.3708","longitude":"43.6473"},{"idlocations":"2","name":"jacks","latitude":"-79.4200","longitude":"43.6555"}]
然而,當我嘗試使用AJAX從JavaScript調用時,收到以下錯誤:
[對象的對象]:parsererrorSyntaxError:在JSON意外標記阿在位置0
JS :
function populateLocations()
{
console.log("inside populate");
//Get other locations from the DB
$.ajax({
url:'http://localhost/VibeSetter/services/getlocations.php',
type: 'POST',
dataType: "json",
timeout: 5000,
success: function(data, status)
{
console.log("inside success");
$.each(data, function(i,item)
{
console.log("inside index");
console.log("item.longitude");
//pass to function to fill array
populateLocationsArray(i+1,item.name, item.longitude, item.latitude);
});
},
error: function(e, ts, et) { console.log(e + " : " + ts + et) }
});
}
function populateLocationsArray(i, name, long, lat)
{
locations[i] = new Array();
locations[i][0] = name;
locations[i][1] = long;
locations[i][2] = lat;
}
有人可以幫我理解爲什麼我不能正確地解析從我的PHP輸出?我嘗試了很多不同的方法,包括刪除'dataType:「json」'並在結果中使用JSON.parse。
在此先感謝
刪除'的print_r($記錄);'爲創建無效的JSON。你只想輸出'echo json_encode($ records);' – Sean