AJAX json unexpected token '

谁说我不能喝 提交于 2019-12-20 02:16:25

问题


I have this code:

    $.ajax({
            dataType: 'text',
            url: '/_/js/answers.json',
            type: "GET",
            success: function (data) {
                alert(data);
                alert(data.code);
                var result = JSON.parse(data);
                var hey = JSON.parse('{"code": 123}'); 
                alert(hey.code);
                alert(result.code);
            },
            error: function () {
                alert("code not found");
            }
        });

In the first alert, alert(data) it shows me '{"code": 123}', in the second alert alert(data.code), it tells me undefined, in the third alert alert(hey.code), it shows me 123, and that's what I want, but in the fourth alert, the console tells me Uncaught SyntaxError: Unexpected token '.
When I change the JSON.parse to $.parseJSON, it does exactly the same things.
I don't know what's wrong, the json is fine (exactly the same as the json in var hey).

I passed the json to the server like this: javascript:

var json = {code: code};
        json = JSON.stringify(json);
        json = {data: json};

        $.ajax({
            url: "/_/js/write-json.php",
            type: "POST",
            dataType: 'json',
            data: json
        }); 

php:

    <?php
    $myFile = "answers.json";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh,var_export($_POST['data'], true));
    fclose($fh);
    ?>

Thanks, bhc11.


回答1:


The ' characters around your JSON make it a JavaScript string and don't form part of the data.

It looks like you have those characters in the JSON that you are requesting over HTTP so there they do form part of the data.

This is not valid JSON. Remove the quotes.

You should have:

{"code": 123}

Not

'{"code": 123}'



回答2:


Try changing dataType to JSON:

$.ajax({
    dataType: 'JSON',
    url: '/_/js/answers.json',
    type: "GET",
    success: function (data) {
        alert(data);
        alert(data.code);
        var result = JSON.parse(data);
        var hey = JSON.parse('{"code": 123}'); 
        alert(hey.code);
        alert(result.code);
    },
    error: function () {
        alert("code not found");
    }
});


来源:https://stackoverflow.com/questions/23172903/ajax-json-unexpected-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!