给标签一个<option>类?API 调用不起作用



我正在使用AJAX和JavaScript/jQuery练习API调用。我目前正在使用随机用户API(https://randomuser.me/)。出于某种原因,当我尝试按国籍调用用户时,AJAX调用无法正确执行。我想知道是不是因为我给标签上了"国籍"的分类?起初,我给这门课贴了标签,但我觉得这不太正确。我哪里错了?我打电话给的每个用户都是澳大利亚人,因为这个国籍恰好是名单上的第一位。有人能给我一些关于如何正确调用API的提示吗?

这是我的HTML:

<h1> Random Person Generator </h1>
    <div class = "info">
        <p> Generate a Random Person! </p>
            <form class = "zipform">
            <p> Nationality? </p>
                <select name = "nationality">
                    <option value = "au" class ="nationality">Australian</option>
                    <option value = "br" class ="nationality">Brazilian</option>
                    <option value = "ca" class ="nationality">Canadian</option>
                    <option value = "ch" class ="nationality">Swiss</option>
                    <option value = "de" class ="nationality">German </option>
                    <option value = "dk" class ="nationality">Norweigan </option>
                    <option value = "es" class ="nationality"> Spanish </option>
                    <option value = "fi" class ="nationality">Finnish</option>
                    <option value = "fr" class ="nationality">French</option>
                    <option value = "gb" class ="nationality">British </option>
                    <option value = "us" class ="nationality">American </option>
                    <option value = "nl" class ="nationality">Dutch </option>
                    <option value = "nz" class ="nationality">New Zealander </option>
                    <option value = "tr" class ="nationality">Turkey</option>
                    </select>
                <button type = "submit" class = "pure_button"> Search </button>
                <input type="reset" value="Reset">
            </form>
            <div class = "rando_facts">
                <p id = "intro"> </p>
                <p id = "name"> </p>
            </div>
    </div>

我的JS/jQuery:

$('.pure_button').click(function(e) { 
e.preventDefault()
    console.log("click noticed")
$.ajax({

    url: "http://api.randomuser.me" + "/?nat=" + $('.nationality').val(),
    type: "GET",
    success: function(data) {
        console.log("This works too")
        debugger
        console.log(data)
        $('#intro').text("Presenting...")
        var firstName = data.results[0].name.first
        var lastName = data.results[0].name.last
        $('#name').text("Name: " + firstName + " " + lastName)
    }
});

});

JSFIDDLE演示-更改国家/地区并点击搜索按钮查看结果

要获得您选择的选项,请使用此选项。如果您只使用类和.val(),您将始终获得第一个选项。

url: "http://api.randomuser.me" + "/?nat=" + $("[name=nationality]").find("option:selected" ).text(),

相关内容

  • 没有找到相关文章

最新更新