我一直在使用ajax取回一些json数据,最近尝试使用fetch执行。 我有不同的响应,我的 ajax 返回一个包含所有键/值对的字符串,而获取查询返回的响应对象根本不包含我的任何键/值 对。 (我在两个示例中请求完全相同的资源并收到不同的响应)
谁能让我知道我做错了什么或者为什么会发生这种情况?
ajax 请求:
$.ajax({
url: "/" + name + ".json",
dataType: "text",
success: function (data) {
console.log(data);
var json = $.parseJSON(data);
var itemArray = [];
$.each(json, function() {
itemArray.push( { value: this.id, label: this.name } );
});
//Populate the List
populateListBox(name, itemArray);
}
});
控制台日志结果:(这是我希望使用获取方法获得的响应)
[{"id":1,"name":"two on two","abbreviation":"2v2","inhouse":true,"length":50,"capacity":1,"price":"50.2","salary":"15.22","url":"http://localhost:3000/en/products/1.json"},{"id":2,"name":"threesome Lessons","abbreviation":"3SUM","inhouse":false,"length":50,"capacity":3,"price":"33.33","salary":"11.11","url":"http://localhost:3000/en/products/2.json"},{"id":3,"name":"Prod1","abbreviation":"PRR1","inhouse":true,"length":22,"capacity":2,"price":"20.0","salary":"20.0","url":"http://localhost:3000/en/products/3.json"}]
获取请求:
fetch("/" + name + ".json")
.then(function(response) {
console.log(response);
return response.json()
}).then(function(json) {
var itemArray = populateItemArray(this, json);
populateListBox(name, itemArray);
}).catch(function(ex) {
console.log('parsing failed', ex)
});
控制台日志结果:(响应一个充满其他对象的对象,但似乎只是一个 html 响应,没有任何我请求的数据)
Response {} body: (...) bodyUsed: false headers: Headers ok: true status: 200 statusText: "OK" type: "basic" url: "http://localhost:3000/login?locale=en" proto: Response
我还在使用 fetch 方法的控制台中收到错误,其内容如下:**
SyntaxError: Unexpected token <
**
希望有人能帮忙。 :)
更新:仔细检查两个请求中的 header 后,我注意到以下内容:我的 AJAX 请求通过 CSRF token 以及 header 中的 cookie 发送。 所有获取请求均以匿名且未经身份验证的方式发出(默认情况下)
所需要做的就是向获取请求添加一个选项,如下所示:
fetch("/" + name + ".json", **{ credentials: 'same-origin' }**)
.then(function(response) {
return response.json()
}).then(function(json) {
var itemArray = populateItemArray(json);
itemArray = sortByLabel(itemArray, 'label');
populateListBox(name, itemArray);
}).catch(function(ex) {
console.log('parsing failed', ex)
});
问题解决了!我花了足够长的时间 - 不需要 CSRF token ,但肯定需要 cookie,因为这使得请求成为经过身份验证的请求。 :)
最佳答案
fetch 需要一个参数来验证其请求:
credentials: 'same-origin'
关于javascript - 使用 fetch 和 ajax 获取 json 会产生不同的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34943025/