【问题标题】:getJSON, Changing the api call url variable before the callgetJSON,在调用前更改 api 调用 url 变量
【发布时间】:2016-12-19 14:42:04
【问题描述】:

我正在尝试使用一个简单的 API 来显示有关国家/地区的信息。在 var apiCall 中,我可以在 url 的末尾硬编码一个国家,getJSON 方法按预期工作并显示信息。

var apiCall = "https://restcountries.eu/rest/v1/name/england";

$.getJSON(apiCall, function(data){

 $("#country").html("Country Name: " + data[0].name + " - " + data[0].alpha2Code);

  $("#capital").html("Capital: " + data[0].capital);

  $("#region").html("Region: " + data[0].region + " - " + data[0].subregion);

  ...

我想在之后添加国家名称,用户输入:

HTML:

<input type="text" placeholder="Country Name" id="inputText"></input>
<button id ="searchButton"> Search </button>

JS

var inputText = $("#inputText");
var apiCall = "https://restcountries.eu/rest/v1/name/";


$("#searchButton").click(function(){
  return apiCall = apiCall + inputText.val();
});

如果我不是返回我做一个console.log,我会得到一个字符串,就像一开始的那样,如果用户输入“england”,那么我会得到“https://restcountries.eu/rest/v1/name/england

$.getJSON(apiCall, function(data){

 $("#country").html("Country Name: " + data[0].name + " - " + data[0].alpha2Code);

  $("#capital").html("Capital: " + data[0].capital);

  $("#region").html("Region: " + data[0].region + " - " + data[0].subregion);

   ...

我该怎么做才能使$("#searchButton").click(function(){} 实际上更改apiCall 的值并使getJSON 再次使用该新值运行?

【问题讨论】:

  • 在构建 api url 后,只需在 click 事件中调用 getJSON 即可。

标签: javascript getjson


【解决方案1】:

这应该可以工作

$("#searchButton").click(function(){
  apiCall = apiCall + inputText.val();
  $.getJSON(apiCall, function(data){ ... });
});

【讨论】:

    【解决方案2】:

    我的建议是将 API 调用重构为自己的函数,如下所示:

     function refreshCountryDetails (country) {
         var url = (apiCall + country);
         $.getJSON(url, function(data) {
             $("#country").html("Country Na......});
         }
      }
    

    然后当用户点击搜索按钮时,我们只需调用我们的 API 包装器即可通过用户输入 (inputText.val()) 获取国家/地区详细信息:

      $("#searchButton").click(function(){
          refreshCountryDetails(inputText.val());
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      • 2013-01-16
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      相关资源
      最近更新 更多