简介
此案例主要是应用jQuery里的$.ajax()方法进行前后端交互
获取url方法
-
搜索 腾讯天气
-
F12 Network 刷新
-
找到这个
右键 点击Open in new tab -
会看到如下页面
-
上面的地址就是我们要用的url
$.ajax()简介
HTML和CSS代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>腾讯天气</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="./腾讯天气.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
.conter{
width: 1000px;
margin: 50px auto;
}
/* 折叠边框 */
table {
border-collapse: collapse;
}
/* 双边框 */
table,
th,
td {
border: 1px solid black;
}
th {
height: 50px;
width: 200px;
font-size: 22px;
}
td{
height: 35px;
text-align: center;
line-height: 35px;
font-size: 18px;
}
</style>
</head>
<body>
<div class="conter">
<table id="add">
<tr>
<th>时间</th>
<th>温度</th>
<th>天气</th>
<th>风向</th>
<th>风力</th>
</tr>
</table>
</div>
</body>
</html>
我们使用表单来做这个样式
关于table:
<table> 标签定义 HTML 表格
一个 HTML 表格包括 <table> 元素,一个或多个 <tr>、<th> 以及 <td> 元素。
<tr> 元素定义表格行,<th> 元素定义表头,<td> 元素定义表格单元。
注意::::
要引用jQuery库 才能使用$.ajax()方法
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
我们如果想要添加结点 就要从后台获取到数据 通过js动态添加
js代码
pc 电脑 xw手机
参数2用哪个传哪个 如果全用的话 传两个 用竖线隔开
不同参数返回的对象不同 可以像代码中全打印处理看看 哪个有用就用哪个
$(function () {
var add=document.getElementById('add');
//对返回的时间进行处理
function time(data){
let times='';
let year=data.substr(0,4);
times=times+year+'年';
let mounth=data.substr(4,2);
times=times+mounth+'月';
let day=data.substr(6,2);
times=times+day+'日';
let hour=data.substr(8,2);
times=times+hour+'时';
return times;
}
$.ajax({
url: 'https://wis.qq.com/weather/common',
type: 'get',
// 只能搜索市、区、县
data: {
source: 'pc',
// weather_type: 'forecast_1h',
// weather_type:'forecast_1h|forecast_24h|index',
weather_type:'forecast_1h|forecast_24h|index|alarm|limit|tips',
province: '陕西省',
city: '西安市',
county: '长安区',
},
dataType: 'jsonp',
success: function (data) {
console.log(data);
let ans = data.data.forecast_1h;
// console.log(ans[0].update_time);
// for (var i in ans)
// console.log(ans[i].update_time);
console.log(data.data.index);
// for (var i in data.data.index)
// console.log( data.data.index[i].name+":"+data.data.index[i].info+":"+data.data.index[i].detail);
for (var i in ans){
let tr=document.createElement("tr");
let td1=document.createElement('td');
td1.innerHTML=time(ans[i].update_time);
let td2=document.createElement('td');
td2.innerHTML=ans[i].degree;
let td3=document.createElement('td');
td3.innerHTML=ans[i].weather_short;
let td4=document.createElement('td');
td4.innerHTML=ans[i].wind_direction;
let td5=document.createElement('td');
td5.innerHTML=ans[i].wind_power;
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
tr.appendChild(td5);
add.appendChild(tr);
}
},
error: function (jqXHR, textStatus, errorThrown) {
// net::ERR_CONNECTION_REFUSED 发生时,也能进入
console.info("网络出错");
}
})
});
如下图 是返回的不同对象