gpt4 book ai didi

javascript - 未捕获的语法错误 : Unexpected token o

转载 作者:行者123 更新时间:2023-11-28 15:19:11 25 4
gpt4 key购买 nike

只是获取一个简单的 .json 文件并解析它,或者不解析它。无论如何,两者都失败了。我尝试了其他线程的解决方案,但没有一个有效。 console.log() 显示一个对象,但我无法使用它。我尝试用几种不同的方式更改 json 但没有成功。这是 .json 文件:

[    {
"name": "Alabama",
"abbreviation": "AL"
},
{
"name": "Alaska",
"abbreviation": "AK"
},
{
"name": "American Samoa",
"abbreviation": "AS"
},
{
"name": "Arizona",
"abbreviation": "AZ"
}]

我觉得还不错。所以我添加了这个函数来使用它:

function fillStates(){

var obj = $.get('states.json');

console.log(obj);

var states = JSON.parse(obj);

//console.log(states);

}

最佳答案

我猜你误解了 jQuery $.get() 方法。它将返回一个 Promise 对象,而不是你想要的数据:

As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

这就是为什么您要为 JSON.parse() 函数提供一个 [object Object]

您必须使用成功回调:

function fillStates(){
var obj = $.get('states.json', function(data) {
// It will be executed in case of sucess
console.log(data);
});
}

关于javascript - 未捕获的语法错误 : Unexpected token o,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32276942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com