【问题标题】:Javascript omdb api won't send all informationJavascript omdb api 不会发送所有信息
【发布时间】:2017-02-26 17:38:03
【问题描述】:

我的问题是每次搜索我只能得到 1 部电影。例如,如果我搜索“哈利波特”,我希望能够获得所有哈利波特电影 JSON 对象。目前我在寻找哈利波特时可以找到哈利波特与死亡圣器。

$("#btnSearch").on("click", function(){
    var input = $("#search").val();
    $(".search-result").find("h3").show();
    $(".search-result").find("h3").text("Laddar...");
    $.ajax({
        url: "http://www.omdbapi.com/?t="+input+"&y=&plot=short&r=json",
        dataType: "JSON"
    }).done(function(data){
        var movie = data.Title;
        var year = data.Year;
        $(".search-result").find("h3").text(movie+"("+year+")");
        $(".search-result").find("h3").show();
    }).fail(function(data){
        $(".search-result").find("h3").text("Något gick fel...");
        $(".search-result").find("h3").show();
    });
});

【问题讨论】:

    标签: javascript jquery json api


    【解决方案1】:

    OMDB Api documentation,您正在使用t 参数执行搜索By Title

    您想使用s 参数请求By Search

    http://www.omdbapi.com/?s=Harry+Potter&y=&plot=short&r=json
    

    它为您提供了一个包含所有匹配数据的数组:

    {
        "Search": [{
            "Title": "Harry Potter and the Deathly Hallows: Part 2",
            "Year": "2011",
            "imdbID": "tt1201607",
            "Type": "movie",
            "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTY2MTk3MDQ1N15BMl5BanBnXkFtZTcwMzI4NzA2NQ@@._V1_SX300.jpg"
        }, {
            "Title": "Harry Potter and the Sorcerer's Stone",
            "Year": "2001",
            "imdbID": "tt0241527",
            "Type": "movie",
            "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BNjQ3NWNlNmQtMTE5ZS00MDdmLTlkZjUtZTBlM2UxMGFiMTU3XkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"
        }, 
        .......
        .......
        .......
        {
            "Title": "Harry Potter and the Order of the Phoenix",
            "Year": "2007",
            "imdbID": "tt0944836",
            "Type": "game",
            "Poster": "http://ia.media-imdb.com/images/M/MV5BN2VhOGI0OTItZjVhMC00MThmLWI5YzEtYTk5ZTFhMjEzOGEzXkEyXkFqcGdeQXVyNzg5OTk2OA@@._V1_SX300.jpg"
        }],
        "totalResults": "77",
        "Response": "True"
    }
    

    您可以使用以下方法获取标题:

    $.ajax({
        url: "http://www.omdbapi.com/?s=Harry+Potter&y=&plot=short&r=json",
        dataType: "JSON"
    }).done(function(data) {
        var search = data.Search;
        for (movie in search) {
            console.log("title : " + search[movie].Title);
        }
    }).fail(function(data) {
        console.log("fail");
    });
    

    【讨论】:

    • 哦,谢谢,就是这样!我可以问一个后续问题吗?我是否需要以某种方式遍历所有 JSON 对象? Surley 我不能只使用我当前的代码 var 'movie = data.Title;'
    • 是的,我已经包含了一个在 ajax 响应中列出标题的示例
    猜你喜欢
    • 2015-03-12
    • 2017-06-21
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2017-07-28
    相关资源
    最近更新 更多