简体   繁体   English

SyntaxError: JSON.parse: AJAX 调用中出现意外字符错误

[英]SyntaxError: JSON.parse: unexpected character error in AJAX call

I'm an engineering intern at a software company, and my current project is to create an HTML page that uses AJAX and PHP to get data from a database.我是一家软件公司的工程实习生,我目前的项目是创建一个 HTML 页面,该页面使用 AJAX 和 PHP 从数据库中获取数据。 I've never posted on this site before, I've always looked for similar posts and used the info I find.我以前从未在这个网站上发帖,我一直在寻找类似的帖子并使用我找到的信息。 I've been looking for a solution to my problem for the last 2 hours or so.在过去 2 个小时左右的时间里,我一直在寻找解决问题的方法。 My AJAX call returns the error: "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data."我的 AJAX 调用返回错误:“SyntaxError:JSON.parse:JSON 数据第 1 行第 1 列的意外字符。”

I've tried lots of things, namely:我尝试了很多东西,即:

  1. Adding dataType: 'json' to the options in $.ajax.将 dataType: 'json' 添加到 $.ajax 中的选项。
  2. Adding header("Content-type: application/json");添加 header("Content-type: application/json"); to the PHP code.到 PHP 代码。
  3. Using console.log($.parseJSON(data)) in the success function.在成功函数中使用 console.log($.parseJSON(data)) 。
  4. Reformatting my code in PHP to include quotes or not include them in the array在 PHP 中重新格式化我的代码以包含引号或不将它们包含在数组中

It seems like the problem is in the formatting of the data my page receives from my PHP script, which is as follows:问题似乎出在我的页面从 PHP 脚本接收的数据的格式上,如下所示:

header('Content-type: application/json');
$testarray = array("Name" => 'America', "Code" => '12345');
echo json_encode($testarray);

In my jquery segment, I want to retrieve JSON data from my PHP script (which will eventually use a MySQL DB) and add the data as elements in my list box, CountriesList.在我的 jquery 段中,我想从我的 PHP 脚本(最终将使用 MySQL 数据库)中检索 JSON 数据并将数据作为元素添加到我的列表框 CountryList 中。 My AJAX call is as follows:我的 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)
            }
             });

It's possible that there are other errors in this code since I haven't been able to debug past this formatting issue.这段代码中可能还有其他错误,因为我无法通过此格式问题进行调试。 When I open the PHP script by itself, I get this as a response: {"Name":"America","Code":"12345"}.当我自己打开 PHP 脚本时,我得到以下响应:{"Name":"America","Code":"12345"}。 Which, as far as I'm aware, is correctly formatted JSON.据我所知,这是正确格式化的 JSON。

I'm at a loss.我不知所措。 Any help is appreciated.任何帮助表示赞赏。

Ill put this as an answer.我把这个作为答案。

As I said in my comment the data variable is already a JSON object.正如我在评论中所说,数据变量已经是一个 JSON 对象。 So you should be able to access each element like so:所以你应该能够像这样访问每个元素:

for(var i in data){
    if(data.hasOwnProperty(i){
        $('#CountriesList').append($("<option></option>").attr("value",data[i].Value).text(data[i].Name));
    }
}

Your test array is just an associative array whereas the javascript is expecting an array of associative arrays.您的测试数组只是一个关联数组,而 javascript 需要一个关联数组数组。 Try尝试

$testarray = array();
$testarray[] = array('Name'=>'America', 'Value'=>'12345');
$testarray[] = array('Name'=>'Europe', 'Value'=>'54321');

The variable data is in JSON format, jQuery does it for you if you add dataType: json or the php header.变量数据采用 JSON 格式,如果您添加 dataType: json 或 php 标头,jQuery 会为您完成。

So you have to change:所以你必须改变:

var jsonData = JSON.parse(data);
By:
var jsonData = data;

If you need POST, this should work (you don't need to parse an array encoded by PHP in json):如果您需要 POST,这应该可以工作(您不需要在 json 中解析由 PHP 编码的数组):

$.post('results.php', // url
        {argOne: "test", argTwo: "test"}, // post data
        function(jsonResponse) { // callback

            $(jsonResponse).each(function (i, element) {
                // do your things
            });
         },'json');

If you can use GET method:如果可以使用 GET 方法:

$.getJSON("results.php", function(jsonResponse) { 

    $(jsonResponse).each(function (i, element) {
        // do your things
    });                           
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AJAX SyntaxError:JSON.parse:意外字符 - AJAX SyntaxError: JSON.parse: unexpected character AJAX请求错误:“SyntaxError:JSON.parse:unexpected character” - AJAX request error: “SyntaxError: JSON.parse: unexpected character” Jquery - Ajax:SyntaxError:JSON.parse:意外字符 - Jquery - Ajax: SyntaxError: JSON.parse: unexpected character json错误:SyntaxError:JSON.parse:意外字符 - json error: SyntaxError: JSON.parse: unexpected character 具有相同数据的Ajax错误(parsererror:SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符) - Ajax error with the same data (parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data) “ SyntaxError:JSON.parse:意外字符”将多个变量从AJAX传递到PHP时出错 - “SyntaxError: JSON.parse: unexpected character” Error when passing multiple variables from AJAX to PHP 错误:SyntaxError:JSON.parse:意外字符+ OAuth - Error :SyntaxError: JSON.parse: unexpected character + OAuth Ajax调用失败,错误为“ SyntaxError:JSON.parse错误:位置0意外输入” - Ajax Call Failing with Error “SyntaxError: JSON.parse Error: Unexpected input at position:0” 语法错误:JSON.parse:意外字符 - SyntaxError: JSON.parse: unexpected character 语法错误:JSON.parse:意外字符 - SyntaxError: JSON.parse: unexpected character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM