【问题标题】:Show the data of JSON response using jQuery使用 jQuery 显示 JSON 响应的数据
【发布时间】:2017-12-06 15:39:14
【问题描述】:

我正在使用一个 API,它会在您搜索某些内容时返回 JSON。它基本上是一个自动完成搜索 API。每当您开始在框中输入内容时,它都会使用 GET 请求访问 API 端点并返回 JSON。假设,你开始输入 "lucky" ,那么请求是 https://autocomplete.clearbit.com/v1/companies/suggest?query=lucky 并且 JSON 响应是

[{"name":"Lucky Brand","domain":"luckybrand.com","logo":"https://logo.clearbit.com/luckybrand.com"},{"name":"LuckyVitamin.com","domain":"luckyvitamin.com","logo":"https://logo.clearbit.com/luckyvitamin.com"},{"name":"Lucky Gunner Ammo","domain":"luckygunner.com","logo":"https://logo.clearbit.com/luckygunner.com"},{"name":"Lucky Orange","domain":"luckyorange.com","logo":"https://logo.clearbit.com/luckyorange.com"},{"name":"Lucky's Market","domain":"luckysmarket.com","logo":"https://logo.clearbit.com/luckysmarket.com"}]

它返回名称、域和徽标。我有一个 html 搜索框,因此,每当您开始输入时,我想在每个项目的一行中显示 logo imagenamedomain。但它没有正确显示。这是我的代码,

html :-

<input type="text" placeholder="type something ..." id="suggest" />

css :-

body{
    padding: 30px;
}

JS :- (我正在使用 jQuery)

$(document).ready(function () {

    $("#suggest").autocomplete({
        delay: 100,
        source: function (request, response) {

            // Suggest URL
            var suggestURL = "https://autocomplete.clearbit.com/v1/companies/suggest?query=%QUERY";
            suggestURL = suggestURL.replace('%QUERY', request.term);

            // JSON Request
            $.ajax({
                method: 'GET',
                dataType: 'json',
                jsonCallback: 'jsonCallback',
                url: suggestURL
            })
            .success(function(data){
                response(data[]); //Here I want to pass all the return 
                                  //items. I can show only one item, 
                                  //like data[1].name but not sure how 
                                  //to go through each item.

            });
        }
    });

});

【问题讨论】:

  • But is not showing properly - 定义正确吗?
  • 有很多方法可以做到这一点,循环或使用一些像地图这样的ES6
  • 我有点困惑,如果端点返回 json,为什么你要尝试使用 jsonpCallback。如果您注意到如果您在控制台中看到任何值的成功处理程序中的控制台日志,并且确实在控制台中看到任何错误,这也会很有帮助。

标签: javascript jquery html css json


【解决方案1】:

您可以使用 forEach() 方法来检查您的响应,例如

data.forEach(function(item) {
    console.log(item.name, item.logo, item.domain);
}); 

更多关于 forEach here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多