Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/429.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果API请求给出字符串,如何告诉JS只替换HTML?_Javascript_Jquery - Fatal编程技术网

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

Javascript 如果API请求给出字符串,如何告诉JS只替换HTML?,javascript,jquery,Javascript,Jquery,我希望JS只在API为这两个字段都提供了实际字符串的情况下填充我的跨度。如果没有,那么我希望它只在一个字段中显示默认值。默认值为“德国” 这是我的密码: $(document).ready(function () { $.get("https://api.ipdata.co?api-key=[APIKEY]", function (response) { city = response.city; country_name = response.country_name;

我希望JS只在API为这两个字段都提供了实际字符串的情况下填充我的跨度。如果没有,那么我希望它只在一个字段中显示默认值。默认值为“德国”

这是我的密码:

$(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"); 
});

德国

首先,您应该使用
text()
而不是
replaceWith()
来设置
div
的内部文本。其次,如果值是
未定义的
空的
、空字符串或任何其他虚假值,则可以使用
|
强制该值。试试这个:

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

首先,您应该使用
text()
而不是
replaceWith()
来设置
div
的内部文本。其次,如果值是
未定义的
空的
、空字符串或任何其他虚假值,则可以使用
|
强制该值。试试这个:

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

如果只想在ajax请求返回两个字段时填充这两个字段,只需将它们包装在If语句中:

$.get("https://api.ipdata.co?api-key=[APIKEY]", (response) => {

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

});

如果只想在ajax请求返回两个字段时填充这两个字段,只需将它们包装在If语句中:

$.get("https://api.ipdata.co?api-key=[APIKEY]", (response) => {

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

});

听起来像是
if
conditional检查响应是否为字符串。如果是这样,则将默认值设置为“x”,否则将默认值设置为“y”。
If(city&&country_name){…}
If(typeof city==“string”){/*code here*/}
可能重复的声音类似于
If
条件检查响应是否为字符串。如果是,则将默认值设置为“x”,否则将默认值设置为“y”。
If(city&&country_name){…}
If(typeof city=='string'){/*code here*/}
可能的重复项