2016-08-01 77 views
2

我一直在做一个简单的天气应用程序项目。用户在一个输入元素中输入一个邮政编码(当点击一个按钮元素时)将对wunderground.com进行API调用。然后从JSON对象中抓取几条数据,并将其串入并插入到DOM中。jQuery .on('click')API调用问题

(function() { 
     var wundergroundAPI = "https://api.wunderground.com/api/3b411ca908826af8/conditions/q/"; 
     var input = $('input'); 

     $('#submit').on('click', function() { 
      var inputValue = input.val(); 
      var weatherByZip = wundergroundAPI += inputValue += '.json'; 
      $.getJSON(weatherByZip, function(json) { 
       $('#temp-f') 
       .text('Temperature: ' + JSON.stringify(json['current_observation']['temp_f']) + ' F'); 
       $('#location') 
       .text('Location: '+ JSON.stringify(json['current_observation']['display_location']['full'])); 
       $('#weather') 
       .text('Weather: ' + JSON.stringify(json['current_observation']['weather'])); 
       input.val(""); 
      }) 
     }); 
    })(); 

jQuery在第一个API调用中工作正常。

GET https://api.wunderground.com/api/3b411ca908826af8/conditions/q/70118.json 

但是,第二个API调用没有。

GET https://api.wunderground.com/api/3b411ca908826af8/conditions/q/70118.json06840.json 

这个问题似乎是在我宣布weatherByZip变量的方式:

var weatherByZip = wundergroundAPI += inputValue += '.json'; 

是我的本意是,weatherByZip变量将被更新(用新inputValue将加上以.json扩展名)每次调用该函数。相反,inputValue和.json会附加到先前创建的变量的末尾。

70118.json06840.json 
70118.json06840.json90210.json 

我该如何解决我的jQuery功能,以纠正这个问题。也就是说,每次调用函数(单击一个按钮元素)时,都会发生新的/更新的API调用?

回答

3

变化+ =至+

var weatherByZip = wundergroundAPI + inputValue + '.json'; 

wundergroundAPI + =装置inputValue的:取wundergroundAPI的现有值和串联的inputValue的背后的值。这就是你的wundergroundAPI不断变长的原因。

+0

谢谢Alain Stoffels!它工作完美。有时候我会陷入一个问题中,忽略简单的解决方案。我一直在考虑使用什么jQuery方法,而不是改变我的操作符。 – GoMagikarp

2
var inputValue = input.val(); 
var weatherByZip = wundergroundAPI + inputValue + '.json'; 

更安全的是修剪inputValue,以删除空格,如果用户添加它们。

var inputValue = input.val().trim(); 

但是,它知道,它不支持在IE8中。你需要一个polyfill。

编辑:作为@Kevin B中提及,jQuery的提供所有平台上工作的修剪方法。如果您需要支持IE8-或者不想复制/粘贴polyfill,请使用它,如下所示:

var inputValue = $.trim(input.val()); 
+0

*知道,但是,它不支持在IE8。*幸运的是,jquery也有一个方法。 –

+0

不知道,谢谢。你知道这个方法是否适用于IE 8? – jonathanGB

+0

是的,因为这就是他们添加它的原因。 http://api.jquery.com/jQuery.trim/ –