gpt4 book ai didi

javascript - 给

转载 作者:行者123 更新时间:2023-12-02 14:39:39 24 4
gpt4 key购买 nike

我正在练习使用 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 DEMO - 更改国家/地区并单击搜索按钮查看结果

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

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

关于javascript - 给 <option> 标签一个类? API 调用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37124382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com