AJAX json意外令牌' [英] AJAX json unexpected token '

查看:63
本文介绍了AJAX json意外令牌'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

    $.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");
            }
        });

在第一个提醒中,提醒(数据)它显示我'{代码:123}',在第二个警告 alert(data.code)中,它告诉我 undefined ,在第三个警告警报(hey.code)中,它显示 123 ,这是我想要什么,但在第四个警报中,控制台告诉我未捕获的SyntaxError:意外的令牌'

当我更改 JSON.parse 到 $。parseJSON ,它做的事情完全一样。

我不知道出了什么问题,json很好(与var中的json完全相同)。


我将json传递给服务器,如下所示:
javascript:

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);
    ?>

谢谢,bhc11。

推荐答案

JSON周围的'字符使其成为JavaScript字符串,不构成数据的一部分。

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

看起来你在JSON中有那些通过HTTP请求的字符,所以他们构成了数据的一部分。

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.

这不是有效的JSON。删除引号。

This is not valid JSON. Remove the quotes.

您应该:

{"code": 123}

'{"code": 123}'

这篇关于AJAX json意外令牌'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆