ajax unexpected token <,javascript - AJAX json unexpected token ' - Stack Overflow

博主在尝试通过Ajax从服务器获取并解析JSON数据时遇到问题。数据在第一个alert中显示正确,但尝试访问`data.code`时返回undefined。然而,当使用相同JSON字符串手动创建对象时,可以成功获取`hey.code`。问题可能在于服务器返回的数据格式或解析过程中。PHP代码显示服务器写入文件的方式,但未展示如何读取和响应JSON数据。
摘要由CSDN通过智能技术生成

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:

$myFile = "answers.json";

$fh = fopen($myFile, 'w') or die("can't open file");

fwrite($fh,var_export($_POST['data'], true));

fclose($fh);

?>

Thanks, bhc11.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值