ajax前端怎么解析json,前端Ajax解析json数据(北京五天内的天气)

该博客演示了一个使用Ajax技术从wthrcdn.etouch.cn获取北京天气预报数据的示例。通过创建XMLHttpRequest对象,实现GET请求,监听服务器响应,并在成功接收数据后解析JSON并展示在页面上,包括日期、天气类型、最高温度、最低温度、风力和风向等信息。
摘要由CSDN通过智能技术生成

/p>

margin: 0;

padding: 0;

}

#weather {

width: 800px;

height: 500px;

margin: 0 auto;

}

.div {

width: 150px;

height: 200px;

background: deepskyblue;

display: inline-block;

line-height: 33px;

text-align: center;

}

/**

* Created by Administrator on 2016/9/3.

*/

function ajaxFun(obj) {

//1.创建请求对象

var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(“Microsoft.XMLHTTP”);

//2.判断请求方法

var method = obj.method.toUpperCase();

if (method == “GET”) {

xhr.open(method, obj.url + “?” + obj.data, true);

xhr.send(null);

} else if (method == “POST”) {

xhr.open(method, obj.url, true);

xhr.send(obj.data);

} else {

console.error(“请求方式有误,请选择get/post中的一种”);

}

//3.监听服务器返回事件

xhr.onreadystatechange = function () {

if (xhr.readyState == 4) {

if (xhr.status >= 200 && xhr.status < 300) {

obj.successFun(xhr.responseText);

} else {

obj.failFun(“请求数据失败”);

console.warn(xhr.status);

}

}

};

}

var divs = document.getElementsByClassName(“div”);

var obj = {

method: “Get”,

url: “http://wthrcdn.etouch.cn/weather_mini?city=北京”,

data: “”,

successFun: successFun,

failFun: failFun

};

ajaxFun(obj);

function successFun(data) {

var resultObj = JSON.parse(data).data;

var forecastArray = resultObj.forecast;

for (var i in forecastArray) {

var array = forecastArray[i];

divs[i].innerHTML = array.date + “
” + array.type + “
” + array.high + “
” + array.low + “
” + array.fengli + “
” + array.fengxiang;

}

}

function failFun(data) {

alert(data);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值