【问题标题】:Parse JSON from API URL using AJAX [closed]使用 AJAX 从 API URL 解析 JSON [关闭]
【发布时间】:2020-06-24 22:32:42
【问题描述】:

我正在尝试使用 ajax 和 'GET' 方法从 API url 显示 JSON。

function getLatestComments() {
        $.ajax({
            type: 'GET',
            url: 'https://***********-API.amazonaws.com/deploymentstage/ride',
            headers: {
                Authorization: authToken
            },
            contentType: 'application/json',
            success: function (data) {
                var text = $("body").append(JSON.stringify(data.records));
                console.log(text);
                text.forEach(function(records) {
                $('#messages').append ('<p> +comments + </p>')
                    
                });
            },
            error: function(err) {
                console.error('Something went wrong: ', err);
            }
        });
    }

来自 URL 的 JSON:

statusCode  200
records 
0   "\"Lets give it a try\""
1   "\"this time its west\""
2   "\"Abcdef\""
3   "\"this is another test\""

headers 
Access-Control-Allow-Origin "*"

【问题讨论】:

  • 让我再发布一次我正在尝试的功能..
  • contentTypeGET 请求中不是必需的,因为您没有发送任何内容。
  • 什么是comments
  • text.forEach() 没有多大意义。您正在循环遍历 $("body") 的元素,而不是 JSON 中的记录。
  • 你可能想要的是data.records.forEach(...)

标签: javascript jquery arrays ajax


【解决方案1】:

您没有正确循环 JSON 数组。 text 包含 jQuery 对象 $("body"),而不是 JSON 响应中的任何内容。

你想要

data.records.forEach(comment => $('#messages').append ('<p>' +comment + '</p>'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多