【发布时间】:2017-04-12 08:11:25
【问题描述】:
我在 JSON.parse() 中有错误,我有 .php 文件,其中包含从数据库中检索数据的方法和用于自动完成功能的 .js 文件,我的 .php 文件以字符串形式返回数据,我需要将其转换为使用 JSON.parse() 对象。
这是我的 php 文件
<?php
include_once("database_conn.php");
function request($conn)
{
$eventstArray = array();
$events = "SELECT *
FROM te_events,te_category,te_venue
WHERE te_events.venueID = te_venue.venueID
AND te_events.catID = te_category_catID
ORDER BY 1
";
$eventsQuery1 = mysqli_query($conn,$events) or DIE (mysqli_error($conn));
while($eventsQuery2 = mysqli_fetch_array($eventsQuery1))
{
$eventstArray[] = array
(
'label' => $eventsQuery2['eventTitle'];
'venue' => $eventsQuery2['venueName'];
'category' => $eventsQuery2['catDesc'];
'price' => $eventsQuery2['eventPrice'];
'description' => $eventsQuery2['eventDescription'];
);
}
return json_encode($eventstArray);
}
echo request($conn);
?>
这是我的 autoComplete.js 文件
$(document).ready(function()
{
'use strict';
$.ajax
({
method: "get",
url: "requestOffer.php"
})
.done(function(data)
{
var offers = JSON.parse(data);
// now we have the data attach the autocomplete
$('#EOffers').autocomplete
({
minLength:3,
source: offers,
select: function(event, ui)
{
$('#chosenEvent').text(ui.item.label);
$('#chosenEvent').text(ui.item.vanue);
}
});
});
});
我无法删除 JSON.parse(),因为我需要将它从字符串转换为对象,希望有人可以帮助我解决这个问题,我真的很感激。
【问题讨论】:
-
data应该已经是 JSON,所以你不需要JSON.parse(),用console.log(data)检查一次 -
这通常发生在您的服务器端出现错误然后响应不是有效 json 的情况下,请先评论这一行
var offers = JSON.parse(data);然后 console.log(data);您的错误将在控制台中 -
我曾尝试删除 JSON.parse,但该功能根本不起作用
-
你能发布一个返回 JSON 的例子吗?
-
Whats your data check network console or debug
标签: javascript php jquery json