0
我的网站上有大约15个以下代码的副本。唯一改变的是URL,经度,纬度和标记变量标题。我该如何削减这个并减少重复?使用AJAX JSON调用API来减少重复使用
$.ajax({
url: "http://api.wunderground.com/api/<api_key>/conditions/q/pws:KCASANFR128.json",
dataType: "jsonp",
success: function(parsed_json) {
var location = parsed_json['current_observation']['observation_location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var weather = parsed_json['current_observation']['weather'].toLowerCase();
var iconUrl = parsed_json['current_observation']['icon_url'];
var iconPic = new MyIcon(iconUrl);
var markerRichmond = new L.Marker(new L.LatLng(37.779806, -122.471895), {icon: iconPic});
markerRichmond.bindPopup("Current temperature in " +location+ " is: " +temp_f+ " and it is " + weather);
map.addLayer(markerRichmond);
}});
诺曼,这几乎正是我一直在寻找我的想法!谢谢!这引发了一些问题,但是......我如何以干净,可重用的方式声明这些变量?我如何确保将每组这些变量打包在一起?我所指的变量标题是'markerRichmond'部分。 –
任何你想让这个ajax调用的地方都可以调用'getWeather'函数,并为变量传递适当的值。例如,要在您的原始文章中进行调用:'getWeather(“http://api.wunderground.com/api/cd48ac26fb540679/conditions/q/pws:KCASANFR128.json”,37.779806,-122.471895,“title”) '。标题是你传递给'markerRichmond.bindPopup'方法的部分吗? –
啊,所以我每次执行这个while的东西时仍然必须传递变量?我想把url,lat,long等放到一个数组或哈希中,然后调用运行这个代码,直到我用尽了所有的值......这有道理吗? –