1ajax
AJAX 是 Asynchronous JavaScript and XML的缩写,即异步的 JavaScript 和 XML。它是jQuery里的方法
作用是可以发起异步请求,到达局部刷新的目的
2.发起ajax请求
写法1:
$.ajax(对象)
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>天气查询</title>
<script src="index.js"></script>
<script src="jquery.2.1.4.min.js"></script> <!-- 导入jQuery -->>
</head>
<body>
<input type="text" value="深圳" id="input_citi">
<input type="button" value="查询" onclick="search()">
<div id="content"></div>
</body>
<script>
function search(){
$city = $('#input_citi').val();
console.log($city);
// 写法1
//ajax用法:$.ajax(对象)
$.ajax({
url: 'http://wthrcdn.etouch.cn/weather_mini?city='+$city,
method: 'get',
dataType:'JSON',
//如果发送的是post请求,可以把请求体放在data对象这里
//data:{},
beforeSend: function () {
// showModal();
},
success: function(res){
//console.log(res)
$("#content").html("");
var forecasts = res.data.forecast;
for(var i=0; i<forecasts.length; i++){
$('#content').append(JSON.stringify(forecasts[i])+"<br>");
}
},
error: function(){
console.log('请求出错');
},
complete: function(){
console.log("complete")
}
});
}
</script>
</html>
注意,如果是发起JSON请求,记得要加上请求头
$.ajax({
url: "/signin",
dataType: 'json',
type: 'post',
contentType: "application/json",
data: JSON.stringify({
"phone_number": '1111'
}),
beforeSend: function () {showLoading()},
success: function (res) {},
error: function (err) {},
complete: function () {hideLoading()},
})
写法2:
$.get(url,data,success(data, status, xhr),dataType).error(func)
$.post(url,data,success(data, status, xhr),dataType).error(func)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>天气查询</title>
<script src="index.js"></script>
<script src="jquery.2.1.4.min.js"></script> <!-- 导入jQuery -->
</head>
<body>
<input type="text" value="深圳" id="input_citi">
<input type="button" value="查询" onclick="search()">
<div id="content"></div>
</body>
<script>
function search(){
$city = $('#input_citi').val();
console.log($city);
// 写法2:
$.get('http://wthrcdn.etouch.cn/weather_mini?city='+$city, function(res,status){
if(status=="success"){
$("#content").html("");
var forecasts = res.data.forecast;
for(var i=0; i<forecasts.length; i++){
$('#content').append(JSON.stringify(forecasts[i])+"<br>");
}
}
},"json").error(function(){
console.log('请求出错')
});
}
</script>
</html>