【发布时间】:2016-02-19 12:01:44
【问题描述】:
我是一家软件公司的工程实习生,我目前的项目是创建一个使用 AJAX 和 PHP 从数据库中获取数据的 HTML 页面。我以前从未在这个网站上发过帖子,我一直在寻找类似的帖子并使用我找到的信息。在过去的两个小时左右,我一直在寻找解决问题的方法。我的 AJAX 调用返回错误:“SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.”
我尝试了很多东西,即:
- 将 dataType: 'json' 添加到 $.ajax 中的选项。
- 添加标头("Content-type: application/json");到 PHP 代码。
- 在成功函数中使用 console.log($.parseJSON(data))。
- 在 PHP 中重新格式化我的代码以包含引号或不将它们包含在数组中
问题似乎在于我的页面从我的 PHP 脚本接收到的数据的格式,如下所示:
header('Content-type: application/json');
$testarray = array("Name" => 'America', "Code" => '12345');
echo json_encode($testarray);
在我的 jquery 段中,我想从我的 PHP 脚本(最终将使用 MySQL 数据库)中检索 JSON 数据,并将数据作为元素添加到我的列表框国家列表中。我的 AJAX 调用如下:
$.ajax({
cache: false,
url: 'results.php',
method: 'POST',
dataType: 'json',
data: "",
success: function (data, textStatus, jqXHR){
//I get an error with the following line
var jsonData = JSON.parse(data);
$(jsonData).each(function (i, element)
{
var htmlSelect = document.getElementById("CountriesList");
var opt = document.createElement("option");
opt.text = element.Name;
opt.value = element.Code;
htmlSelect.options.add(opt);
});
},
error: function(jsXHR, textStatus, errorThrown)
{
alert('Error: ' + errorThrown)
}
});
此代码中可能存在其他错误,因为我无法通过此格式问题进行调试。当我自己打开 PHP 脚本时,我得到这个响应:{"Name":"America","Code":"12345"}。据我所知,其中的 JSON 格式正确。
我很茫然。任何帮助表示赞赏。
【问题讨论】:
-
是响应不是json我认为你不需要解析它。试试 console.log(JSON.stringify(data));如果输出的是 JSON 字符串,你已经得到了 JSON
标签: javascript php jquery json ajax