我的网站上有大约15份以下代码。唯一改变的是网址,经度,纬度和标记变量标题。我怎样才能把它砍掉并减少重复?
$.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);
}});
答案 0 :(得分:1)
您可以创建一个函数来接收这些变量并将它们提供给ajax调用。那么你只需要一个这个ajax块的副本,你可以通过调用getWeather
函数来调用它
function getWeather(url, lat, long, title){
$.ajax({
url: url,
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(lat, long), {icon: iconPic});
markerRichmond.bindPopup(title);
map.addLayer(markerRichmond);
}
});
}
我不确定我是否在这里正确处理了标题,但你明白了。如果您了解标题可能如何变化,我可以相应地修改代码。
希望这会有所帮助。
答案 1 :(得分:0)
var current_observation = parsed_json['current_observation'];
这也缩短了解析的时间。 然后您可以将您的变量称为
current_observation['observation_location']['city'];