创建一个支持AJAX的数据驱动应用程序

时间:2017-06-05 03:20:34

标签: javascript jquery html ajax getelementbyid

当我输入艺术家并点击按钮时,我应该以一种美观的格式获得一个很好的歌曲列表。

我的错误是:   每按一下按钮都没有任何回报,我不知道为什么会这样。

HTML文件

<!DOCTYPE html>
<html>
<head>
    <title>Songs</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet"     href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
    </script>
    <script
    src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
    </script>
    <script src="ajaxfunctions.js"></script>
</head>
<body>
    <div class="container">
        <h2>Songs </h2>
        <br/>
        <p>Try entering an artist to find their songs</p>
        <div>
            <div id="musicbox" class="control-group">
                <label for="songs">artistr</label>
                <input type="text" name="songs" id="songs" placeholder="Type an artist to their songs" />
            </div>
        </div>
        <br />
        <div>
            <button class='btn btn-success btn-large' onclick="Music('songs')">Find Songs</button>
        </div>
        <br />
        <div>
        </div>
    </div>
</body>
</html>

JS档案

function Music(songs) {
    var yourmusic = document.getElementById(songs).value;
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function () {
        if (this.readyState === 4) {
            if(this.status === 200) {
                displayMusic(this.responseText);
            } else if (this.status === 404){
                displayMusic('{ "songs" : "none" }');
            } else {
                console.log("We have a problem: " + this.status);
            }
        } else {
        }
    };
    var url = " https://api.mixcloud.com/discover/funk/";
    httpRequest.open("GET", url, true);
    httpRequest.send();
}

function displayMusic(data){
    var music = JSON.parse(data);
    if(music.songs === "none") {
        document.getElementById("songs").className = "alert alert-warning";\
        document.getElementById("songs").innerHTML ="there are no songs for this artist"
        document.getElementById("songs").innerHTML = "The songs are" + music;
    } else {
        document.getElementById("songs").className = "alert alert-success";
        document.getElementById("songs").innerHTML = "The songs are" + music;
    }
}

1 个答案:

答案 0 :(得分:0)

您检查代码:

document.getElementById("music") // element id "music" not exist