根据用户选择的城市,显示这个城市的天气信息。api接口:http://wthrcdn.etouch.cn/weather_mini?city=深圳 注意:这个接口已经服务端打破了同源。
效果:
html :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
p {
width: 100px;
height: 200px;
background: cadetblue;
float: left;
margin-right: 20px;
}
</style>
</head>
<body>
请选择你所在的城市:
<select value="赣州">
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="广州">广州</option>
<option value="深圳">深圳</option>
<option value="珠海">珠海</option>
<option value="厦门">厦门</option>
<option value="杭州">杭州</option>
</select>
未来五天的天气
<div id="box"></div>
<script type="text/javascript" src="day_19ajax请求数据.js"></script>
<script type="text/javascript">
var sel = document.querySelector("select");
var div = document.querySelector("div");
sel.onchange = function(){
var city = sel.value;
div.innerHTML = "";
ajax.get({
url: "http://wthrcdn.etouch.cn/weather_mini?city=" + encodeURIComponent(city),
onSuccess: function(result) {
var obj = JSON.parse(result);
var smg = obj.data.forecast;
for(var s of smg) {
var date = s.date;
var high = s.high;
var fengli = s.fengli;
var low = s.low;
var fengxiang = s.fengxiang;
var type = s.type;
var p = document.createElement("p");
p.innerHTML = date + "<br>" + type + "<br>"
+ high + "<br>" + low + "<br>" + fengxiang + "<br>" + fengli;
div.appendChild(p);
}
}
})
}
</script>
</body>
</html>
JS ajax方法:
ajax = {
/*使用get方法进行ajax请求*/
get: function (option){
if (!option.url) return; //
if (typeof option.onSuccess != "function") return;
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")
xhr.open("GET", option.url, true);
xhr.onreadystatechange = function (){
if (xhr.readyState == 4){
if (xhr.status == 200){
option.onSuccess(xhr.responseText);
}else{
if (typeof option.onFail == "function"){
option.onFail(xhr.responseText);
}
}
}
}
xhr.send(null);
},
/*使用post方式进行ajax请求*/
post: function (option){
if (!option.url) return; //
if (typeof option.onSuccess != "function") return;
var xhr = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Micosoft.XMLHTTP")
xhr.open("POST",option.url,true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
option.onSuccess(xhr.responseText);
}else{
if(typeof option.onFail == "function"){
option.onFail(xhr.responseText);
}
}
}
}
//如果是使用的post提交表单数据,需要添加这个请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(option.data);
}
}