如何从REST国家api中按名称搜索一个国家?

时间:2018-11-11 21:05:20

标签: javascript jquery ajax async-await fetch-api

我需要针对REST国家的API使用async await + fetch来实现以下两个目的:

1)点击“显示所有国家”,绘制所有国家(有效!)

2)用户输入并获取单个国家/地区后,点击“按名称搜索” <-这个我无法成功...这非常令人困惑,因为我必须对除请求之外的所有内容都使用jquery。我会粘贴我的代码,希望任何人都能帮助我,我很绝望!

$("button").click(function() {
	$("#display").empty();
	getCountries()
	.then(result =>{
		result.forEach(element => {
			var card = $('<div>', {class: "card"}).appendTo('#display');
			var country = $('<div>', {class: "country-info"}).appendTo(card);
			var img = $('<div>', {class: "img"}).appendTo(country);
			$('<img>', {src: element.flag}).appendTo(img);
			var text = $('<div>', {class: "right-text"}).appendTo(country);
			$('<p>', {text: "Name: " + element.name}).appendTo(text);
			$('<p>', {text: "Top Level Domain: " + element.topLevelDomain}).appendTo(text);
			$('<p>', {text: "Capital: " + element.capital}).appendTo(text);
			$('<h4>', {text: 'Currencies:'}).appendTo(text);
			element.currencies.forEach(element =>{
				var currencies = $('<div>', {
					class: "currencies"
				}).appendTo(text);
				$('<span>', {text: element.code + " "}).appendTo(currencies);
			})
		});
		
	})
	.catch(err =>console.log(err));
});


async function getCountries(){
	const response = await fetch(`https://restcountries.eu/rest/v2/all`);
	const responseData = await response.json();

	return responseData;
}

async function getCountryName(){
	const response = await fetch(`https://restcountries.eu/rest/v2/name/`);
	const responseData = await response.json();

	return responseData;
}
img {
	width: 100%;
}
.img {
	width: 30%;
}
.country-info {
	display: flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"/>

<h1 class="text-muted text-center"> Countries of the World</h1>
<div class="container">
	<form>
		<div class="form-group col-xs-12">
			<label for="name">Enter country</label>
			<input class="form-control" type="search" name="name">
			<br/>
			<input class="form-control" type="submit" id="search" value="Search by Name">
		</div>
	</form>
	<button id="show" class="btn btn-success form-control">Show All</button>
	<div id="display" class="col-xs-12"></div>
</div>

2 个答案:

答案 0 :(得分:0)

你在这里...

这里的问题与您的第一个获取请求不同,这需要用户的一些输入->因此,表单...您必须在提交时捕获其输入并将其附加到searchURL->因此,如果他们输入西班牙,则您的最终输入网址结尾为https://restcountries.eu/rest/v2/name/Spain等,等等

基本上,您需要研究如何处理表单提交...您可以尝试剖析和理解我在下面提供的代码...

目前这只是console.loging不会返回数据并将其附加到DOM,但这应该足以使您朝正确的方向前进...

const searchURL = 'https://restcountries.eu/rest/v2/name/';

async function getCountryName(name) {
  const url = searchURL + name;
  const response = await fetch(url);
  const responseData = await response.json();

  console.log(responseData);
}

function watchForm() {
  $('form').submit(event => {
    event.preventDefault();
    const searchTerm = $('#js-search-term').val();
    getCountryName(searchTerm);
  });
}

$(watchForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="text-muted text-center">Countries of the World</h1>
    <div class="container">
      <form id="js-form">
        <div class="form-group col-xs-12">
          <label for="name">Enter country</label>
          <input class="form-control" type="search" name="search-term" id="js-search-term" /> <br />
          <input
            class="form-control"
            type="submit"
            id="search"
            value="Search by Name"
          />
        </div>
      </form>
      <button id="show" class="btn btn-success form-control">Show All</button>
      <div id="display" class="col-xs-12"></div>
    </div>

答案 1 :(得分:0)

$("form").submit(function(e) {
e.preventDefault();
	$("#display").empty();
let name =  e.currentTarget.name.value;
if(!name){

alert("Enter name");

return;
}
	getCountryName(name)
	.then(result =>{
		result.forEach(element => {
			var card = $('<div>', {class: "card"}).appendTo('#display');
			var country = $('<div>', {class: "country-info"}).appendTo(card);
			var img = $('<div>', {class: "img"}).appendTo(country);
			$('<img>', {src: element.flag}).appendTo(img);
			var text = $('<div>', {class: "right-text"}).appendTo(country);
			$('<p>', {text: "Name: " + element.name}).appendTo(text);
			$('<p>', {text: "Top Level Domain: " + element.topLevelDomain}).appendTo(text);
			$('<p>', {text: "Capital: " + element.capital}).appendTo(text);
			$('<h4>', {text: 'Currencies:'}).appendTo(text);
			element.currencies.forEach(element =>{
				var currencies = $('<div>', {
					class: "currencies"
				}).appendTo(text);
				$('<span>', {text: element.code + " "}).appendTo(currencies);
			})
		});
		
	})
	.catch(err =>console.log(err));
});

async function getCountries(){
	const response = await fetch(`https://restcountries.eu/rest/v2/all`);
	const responseData = await response.json();

	return responseData;
}

async function getCountryName(name){
	const response = await fetch(`https://restcountries.eu/rest/v2/name/${name}`);
	const responseData = await response.json();
debugger
	return responseData;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"/>

<h1 class="text-muted text-center"> Countries of the World</h1>
<div class="container">
	<form>
		<div class="form-group col-xs-12">
			<label for="name">Enter country</label>
			<input class="form-control" type="search" name="name">
			<br/>
			<input class="form-control" type="submit" id="search" value="Search by Name">
		</div>
	</form>
	<button id="show" class="btn btn-success form-control">Show All</button>
	<div id="display" class="col-xs-12"></div>
</div>