Javascript SyntaxError: JSON.parse: JSON 数据第 1 行第 1 列的意外字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25743994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:48:47  来源:igfitidea点击:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

javascriptphpjqueryajaxjson

提问by levent kaya

I've spend over 6 hours to find an exception or a special character to find in my code but I couldn't. I checked every similar messages in here.

我花了 6 多个小时在我的代码中找到异常或特殊字符,但我找不到。我在这里检查了所有类似的消息。

I'm sending the form with magnific popup. First I'm using inline popup to open my form than I'm sending all inputs to main.js to validate.

我正在发送带有 magnific popup 的表单。首先,我使用内联弹出窗口打开我的表单,而不是将所有输入发送到 main.js 以进行验证。

So, I just need a third-eye.

所以,我只需要第三只眼。

I've got: index.html, register.php, main.js

我有:index.html, register.php,main.js

Here's the code

这是代码

FORM

形式

JS/AJAX

JS/AJAX

PHP-register.php

PHP-register.php

Here goes the error messages

这是错误消息

JSON Outputjson

JSON 输出json

Chrome Console:

Chrome 控制台:

chrome

铬合金

Firefox console :firefox

火狐控制台:火狐



What am i missing?

我错过了什么?

采纳答案by James Lalor

The fact the character is a < make me think you have a PHP error, have you tried echoing all errors.

字符是 < 的事实让我认为您有 PHP 错误,您是否尝试回显所有错误。

Since I don't have your database, I'm going through your code trying to find errors, so far, I've updated your JS file

由于我没有你的数据库,我正在检查你的代码试图找出错误,到目前为止,我已经更新了你的 JS 文件

$("#register-form").submit(function (event) {

    var entrance = $(this).find('input[name="IsValid"]').val();
    var password = $(this).find('input[name="objPassword"]').val();
    var namesurname = $(this).find('input[name="objNameSurname"]').val();
    var email = $(this).find('input[name="objEmail"]').val();
    var gsm = $(this).find('input[name="objGsm"]').val();
    var adres = $(this).find('input[name="objAddress"]').val();
    var termsOk = $(this).find('input[name="objAcceptTerms"]').val();

    var formURL = $(this).attr("action");


    if (request) {
        request.abort(); // cancel if any process on pending
    }

    var postData = {
        "objAskGrant": entrance,
        "objPass": password,
        "objNameSurname": namesurname,
        "objEmail": email,
        "objGsm": parseInt(gsm),
        "objAdres": adres,
        "objTerms": termsOk
    };

    $.post(formURL,postData,function(data,status){
        console.log("Data: " + data + "\nStatus: " + status);
    });

    event.preventDefault();
});

PHP Edit:

PHP编辑:

 if (isset($_POST)) {

    $fValid = clear($_POST['objAskGrant']);
    $fTerms = clear($_POST['objTerms']);

    if ($fValid) {
        $fPass = clear($_POST['objPass']);
        $fNameSurname = clear($_POST['objNameSurname']);
        $fMail = clear($_POST['objEmail']);
        $fGsm = clear(int($_POST['objGsm']));
        $fAddress = clear($_POST['objAdres']);
        $UserIpAddress = "hidden";
        $UserCityLocation = "hidden";
        $UserCountry = "hidden";

        $DateTime = new DateTime();
        $result = $date->format('d-m-Y-H:i:s');
        $krr = explode('-', $result);
        $resultDateTime = implode("", $krr);

        $data = array('error' => 'Yükleme S?ras?nda Hata Olu?tu');

        $kayit = "INSERT INTO tbl_Records(UserNameSurname, UserMail, UserGsm, UserAddress, DateAdded, UserIp, UserCityLocation, UserCountry, IsChecked, GivenPasscode) VALUES ('$fNameSurname', '$fMail', '$fGsm', '$fAddress', '$resultDateTime', '$UserIpAddress', '$UserCityLocation', '$UserCountry', '$fTerms', '$fPass')";
        $retval = mysql_query( $kayit, $conn ); // Update with you connection details
            if ($retval) {
                $data = array('success' => 'Register Completed', 'postData' => $_POST);
            }

        } // valid ends
    }echo json_encode($data);

回答by HockeyJ

For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.

为了寻求解决类似问题的搜索者的利益,如果您的输入是空字符串,您可能会收到类似的错误。

e.g.

例如

var d = "";
var json = JSON.parse(d);

or if you are using AngularJS

或者如果您使用的是 AngularJS

var d = "";
var json = angular.fromJson(d);

In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.

在 chrome 中,它导致“Uncaught SyntaxError: Unexpected end of input”,但 Firebug 将其显示为“JSON.parse:JSON 数据的第 1 行第 1 列的数据意外结束”。

Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.

当然大多数人不会被这个发现,但我没有保护这个方法,它导致了这个错误。

回答by Алексей Полоскин

Remove

消除

 dataType: 'json'

replacing it with

将其替换为

 dataType: 'text'

回答by Dumitrascu Alexandru

I have the exact same issue and I've found something. I've commented the line :

我有完全相同的问题,我找到了一些东西。我已经评论了这一行:

dataType : 'json',

数据类型:'json',

after that it was successful but... when I did console.log(data) it returned the main index.html.

之后它成功了但是......当我做console.log(data)时它返回了主index.html。

That's why you have "Unexpected token <" error and it cannot parse.

这就是为什么您有“意外的令牌 <”错误并且无法解析的原因。

回答by Amit Patekar

Changing the data type to text helped dataType: 'text'

将数据类型更改为文本帮助 dataType: 'text'

I have check with JSONlint and my json format was proper. Still it was throwing error when I set dataType: 'json'

我已经检查过 JSONlint 并且我的 json 格式是正确的。当我设置时它仍然抛出错误dataType: 'json'

JSON Data: {"eventinvite":1,"groupcount":8,"totalMessagesUnread":0,"unreadmessages":{"378":0,"379":0,"380":0,"385":0,"390":0,"393":0,"413":0,"418":0}} 

回答by Mickael Largement

Sending JSON data with NodeJS on AJAX call :

在 AJAX 调用上使用 NodeJS 发送 JSON 数据:

$.ajax({
    url: '/listClientsNames',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify({foo:'bar'})
}).done(function(response){
    console.log("response :: "+response[0].nom);
});

Be aware of removing white spaces.

请注意删除空格。

app.post("/listClientsNames", function(req,res){

        var querySQL = "SELECT id, nom FROM clients";   
        var data = new Array();

        var execQuery = connection.query(querySQL, function(err, rows, fields){

            if(!err){
                for(var i=0; i<25; i++){
                    data.push({"nom":rows[i].nom});         
                }
                res.contentType('application/json');
                res.json(data); 
            }else{  
                console.log("[SQL005] - Une erreur est survenue");
            }

        });

});

回答by akshay_sushir

I have got same Error while fetch data from json filesee attached link

我在从 json 文件中获取数据时遇到了同样的错误,请参阅附加链接

"SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"

So, i check the path of the json file which isn't correct,

所以,我检查了不正确的json文件的路径,

const search = document.getElementById("search");
const matchList = document.getElementById("match-list");

//search json data and filter
const searchStates = async searchText => {
    const res = await fetch('../state.json');
    const states = await res.json();
    console.log(states);
}

search.addEventListener('input', () => searchStates(search.value));

so that i changed the path of the file

所以我改变了文件的路径

const res = await fetch('./state.json');

& it gives me array back as a result. so, check your path & try changed it. It will work in my case. I hope that's works..

& 结果它给了我数组。因此,请检查您的路径并尝试更改它。它适用于我的情况。我希望那有效..

回答by MarkT

Try using MYSQLI_ASSOCinstead MYSQL_ASSOC... usually the problem is solved changing that

尝试使用MYSQLI_ASSOC而不是 MYSQL_ASSOC ......通常问题解决了改变

Good luck!

祝你好运!

回答by user7572039

Even if your JSON is ok it could be DB charset (UTF8) problem. If your DB's charset/collation are UTF8 but PDO isn't set up properly (charset/workaround missing) some à / è / ò / ì / etc. in your DB could break your JSON encoding (still encoded but causing parsing issues). Check your connection string, it should be similar to one of these:

即使您的 JSON 没问题,也可能是 DB 字符集 (UTF8) 问题。如果您的数据库的字符集/排序规则是 UTF8,但 PDO 设置不正确(缺少字符集/解决方法),您的数据库中的某些 à / è / ò / ì / 等可能会破坏您的 JSON 编码(仍在编码但会导致解析问题)。检查您的连接字符串,它应该类似于以下之一:

$pdo = new PDO('mysql:host=hostname;dbname=DBname;**charset=utf8**','username','password'); // PHP >= 5.3.6

$pdo = new PDO('mysql:host=hostname;dbname=DBname','username','password',**array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")**); // older versions

P.S. Outdated but still could be helpful for people who're stuck with "unexpected character".

PS 过时了,但仍然可以帮助那些被“意外角色”困住的人。

回答by Prahlad

May be its irrelevant answer but its working in my case...don't know what was wrong on my server...I just enable error log on Ubuntu 16.04 server.

可能是它不相关的答案,但它在我的情况下工作......不知道我的服务器出了什么问题......我只是在 Ubuntu 16.04 服务器上启用错误日志。

//For PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);