简体   繁体   English

如果 API 请求给出字符串,如何告诉 JS 仅替换 HTML?

[英]How to tell JS to only replace HTML if API request gave string?

I want JS to fill my span only if API gave an actual string for both fields.仅当 API 为两个字段都提供了实际字符串时,我才希望 JS 填充我的范围。 If it didn't then I want it to display default value only in one field.如果没有,那么我希望它仅在一个字段中显示默认值。 The default value is "Germany".默认值为“德国”。

Here is my code:这是我的代码:

$(document).ready(function () {
  $.get("https://api.ipdata.co?api-key=[APIKEY]", function (response) { 
    city = response.city;
    country_name = response.country_name;
    $("#city").html(city);
    $("#country_name").replaceWith(country_name);
  }, "jsonp"); 
});
<span id="city"></span>
<span id="country_name">Germany</span>

Firstly you should use text() not replaceWith() to set the innerText of the div .首先,您应该使用text()而不是replaceWith()来设置div的 innerText 。 Secondly, you can use ||其次,您可以使用|| to coerce a value if it's undefined , null , an empty string or any other falsy value.如果它是undefinednull 、空字符串或任何其他虚假值,则强制它的值。 Try this:尝试这个:

$("#city").text(city || '');
$("#country_name").text(country_name || 'Germany');

If you want to populate both fields only if both fields are returned from the ajax request, you can simply wrap them in an if statement:如果您只想在 ajax 请求返回两个字段时填充这两个字段,您可以简单地将它们包装在 if 语句中:

$.get("...api.site.here", function(response){

 if(response.city && response.country_name){
  // same code here
 }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM