Ajax:不刷新浏览器的情况下加载数据
1.原生JS中的Ajax
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp=new XMLHttpRequest();
}
else
{
// IE6, IE5 浏览器执行代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/try/ajax/ajax_info.txt",true);
xmlhttp.send();
}
过程:
1.创建ajax中xhr(xmlHttpRequest)对象,注意兼容性;
2.xhr请求
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
get请求
xmlhttp.open("GET","/try/ajax/demo_get2.php?fname=Henry&lname=Ford",true);
xmlhttp.send();
post请求:一般是open和send。setRequestHeader用于添加HTTP头,可以像变淡那样post数据;
xmlhttp.open("POST","/try/ajax/demo_post2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
3.xhr响应
获得服务器的响应,使用XMLHttpRequest对象的responseText(字符串形式)或responseXML(xml形式,涉及xml的解析)。
4.onreadystatechange事件5
每当 readyState 改变时,就会触发 onreadystatechange 事件。readyState 属性存有 XMLHttpRequest 的状态信息。
5.使用回调函数
回调函数是一种以参数形式传递给另一个函数的函数。
网站上存在多个 AJAX 任务,那么应该为创建 XMLHttpRequest 对象编写一个标准的函数,并为每个 AJAX 任务调用该函数。
该函数调用应该包含 URL 以及发生 onreadystatechange 事件时执行的任务(每次调用可能不尽相同)
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// IE7+, Firefox, Chrome, Opera, Safari 代码
xmlhttp=new XMLHttpRequest();
}
else
{// IE6, IE5 代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("/try/ajax/ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>使用 AJAX 修改文本内容</h2></div>
<button type="button" onclick="myFunction()">修改内容</button>
</body>
</html>
2.jQuery中的ajax
1.$.ajax()是jQuery中底层ajax实现,更高层的是$.get和$.post方法;
$(document).ready(function(){
$("#b01").click(function(){
htmlobj=$.ajax({url:"/jquery/test1.txt",async:false});
$("#myDiv").html(htmlobj.responseText);
});
});
2.$.get方法,请求成功时的操作,如果想有请求失败时的操作,要使用$.ajax()
$(selector).get(url,data,success(response,status,xhr),dataType)
$("button").click(function(){
$.get("demo_ajax_load.txt", function(result){
$("div").html(result);
});
});
是$.ajax的简写
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
例子:
$.get("test.cgi", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
3.$.post方法
$("input").keyup(function(){
txt=$("input").val();
$.post("demo_ajax_gethint.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
是下面的简写
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
实例可参考W3C:http://www.w3school.com.cn/jquery/ajax_post.asp
4.$.getJSON()
通过HTTP get请求获得json数据
jQuery.getJSON(url,data,success(data,status,xhr))
$("button").click(function(){
$.getJSON("demo_ajax_json.js",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
是下面的简写
$.ajax({
url: url,
data: data,
success: callback,
dataType: json
});
5.两个重要的方法
.serialize() 将表单内容序列化为字符串;
.serializeArray() 序列化表单元素,返回JSON数据结构数据。
3.VUE中的Ajax
vue本身不支持ajax请求,需要借助vue-resource,axios插件
vue2官方推荐axios,是一个基于Promise的HTTP请求客户端,不再对vue-resource进行维护和更新;
axios([options])
axios.get(url[,options]);
传参方式:
1.通过url传参
2.通过params选项传参
axios.post(url,data,[options]);
axios默认发送数据时,数据格式是Request Payload,并非我们常用的Form Data格式,
所以参数必须要以键值对形式传递,不能以json形式传参
传参方式:
1.自己拼接为键值对
2.使用transformRequest,在请求发送前将请求数据进行转换
3.如果使用模块化开发,可以使用qs模块进行转换
axios本身并不支持发送跨域的请求,没有提供相应的API,作者也暂没计划在axios添加支持发送跨域请求,所以只能使用第三方库
发送Ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送AJAX请求</title>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script src="js/vue-resource.min.js"></script>
<script>
window.onload=function(){
new Vue({
el:'#itany',
// data:{
// user:{
// // name:'alice',
// // age:19
// },
// uid:''
// },
methods:{
send(){
axios({
method:'get',
url:'user.jsonoo'
}).then(function(resp){
console.log(resp.data());
}).catch(resp => {
console.log(resp);
console.log('请求失败:'+resp.status+','+resp.statusText);
});
},
sendGet(){
// axios.get('server.php?name=tom&age=23')
// axios.get('server.php',{
// params:{
// name:'alice',
// age:19
// }
// })
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log('请求失败:'+err.status+','+err.statusText);
});
},
sendPost(){
// axios.post('server.php',{
// name:'alice',
// age:19
// })
// axios.post('server.php','name=alice&age=20&') //方式1
axios.post('server.php',this.user,{
transformRequest:[
function(data){
let params='';
for(let index in data){
params+=index+'='+data[index]+'&';
}
return params;
}
]
})
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log('请求失败:'+err.status+','+err.statusText);
});
},
getUserById(uid){
axios.get(`https://api.github.com/users/${uid}`)
.then(resp => {
// console.log(resp.data);
this.user=resp.data;
});
},
sendJSONP(){
//https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=a
this.$http.jsonp('https://sug.so.360.cn/suggest',{
params:{
word:'a'
}
}).then(resp => {
console.log(resp.data.s);
});
},
sendJSONP2(){
//https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&json=1&p=3&sid=1420_21118_17001_21931_23632_22072&req=2&csor=1&cb=jQuery110208075694879886905_1498805938134&_=1498805938138
this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
params:{
wd:'a'
},
jsonp:'cb' //百度使用的jsonp参数名为cb,所以需要修改
}).then(resp => {
console.log(resp.data.s);
});
}
}
});
}
</script>
</head>
<body>
<div id="itany">
<button @click="send">发送AJAX请求</button>
<button @click="sendGet">GET方式发送AJAX请求</button>
<!--<button @click="sendPost">POST方式发送AJAX请求</button>-->
<!--<hr>-->
<!--<br>-->
<!--GitHub ID: <input type="text" v-model="uid">-->
<!--<button @click="getUserById(uid)">获取指定GitHub账户信息并显示</button>-->
<!--<br>-->
<!--姓名:{{user.name}} <br>-->
<!--头像:<img :src="user.avatar_url" alt="">-->
<!---->
<!--<hr>-->
<!--<button @click="sendJSONP">向360搜索发送JSONP请求</button>-->
<!--<button @click="sendJSONP2">向百度搜索发送JSONP请求</button>-->
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送AJAX请求</title>
<style>
.current{
background-color:#ccc;
}
</style>
<script src="js/vue.js"></script>
<script src="js/vue-resource.min.js"></script>
<script>
window.onload=function(){
new Vue({
el:'#itany',
data:{
keyword:'',
myData:[],
now:-1 //当前选中项的索引
},
methods:{
getData(e){
//如果按方向键上、下,则不发请求
if(e.keyCode==38||e.keyCode==40)
return;
this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
params:{
wd:this.keyword
},
jsonp:'cb'
}).then(resp => {
this.myData=resp.data.s;
});
},
changeDown(){
this.now++;
this.keyword=this.myData[this.now];
if(this.now==this.myData.length){
this.now=-1;
}
},
changeUp(){
this.now--;
this.keyword=this.myData[this.now];
if(this.now==-2){
this.now=this.myData.length-1;
}
}
}
});
}
</script>
</head>
<body>
<div id="itany">
<!--判断键盘事件-->
<input type="text" v-model="keyword" @keyup="getData($event)" @keydown.down="changeDown" @keydown.up.prevent="changeUp">
<ul>
<li v-for="(value,index) in myData" :class="{current:index==now}">
{{value}}
</li>
</ul>
<p v-show="myData.length==0">暂无数据....</p>
</div>
</body>
</html>