使用 fetch 和 ajax 获取 JSON 会产生不同的响应

getting json with fetch and ajax yields different responses

本文关键字:响应 fetch ajax 获取 JSON 使用      更新时间:2023-09-26

我一直在使用ajax来获取一些json数据,最近尝试使用fetch实现。我有不同的响应,我的 ajax 返回一个包含我所有键/值对的字符串,而 fetch 查询返回的响应对象根本不包含我的任何键/值对。(我在两个示例中请求完全相同的资源并收到不同的响应)

谁能让我知道我做错了什么或为什么会发生这种情况?

阿贾克斯请求:

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

控制台日志结果:(这是我想要使用 fetch 方法获得的响应)

[{"id":1,"name":"二对二","缩写":"2v2","内部":true,"length":50,"

capacity":1,"price":"50.2","salary":"15.22","url":"http://localhost:3000/en/products/1.json"},{"id":2,"name":"三人行课程","缩写":"3SUM","内部":假,"长度":50,"容量":3,"价格":"33.33","薪水":"11.11","url":"http://localhost:3000/en/products/2.json"},{"id":3,"名称":"Prod1","缩写":"PRR1","内部":true,"长度":22,"容量":2,"价格":"20.0","薪水":"20.0","网址":"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 响应,没有任何我请求的数据)

响应 {} 正文:(... 身体使用:假 标头:标头 确定:真 状态: 200 状态文本:"正常" 类型:"基本" 网址:"http://localhost:3000/login?locale=en" 原型:响应

我还在使用 fetch 方法在控制台中收到错误,其中指出以下内容:**

语法错误:意外的令牌<</p>

**

希望有人能帮忙。 :)

更新:在仔细检查了两个请求中的标头后,我注意到以下内容:我的 AJAX 请求通过 CSRF 令牌以及标头中的 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 令牌,但绝对需要 cookie,因为这是允许请求经过身份验证的请求的原因。:)

fetch 需要一个参数来使其请求经过身份验证:

凭据:"同源"

不确定,也许将数据类型:"文本"更改为"json"?