1.使用fetch()访问
fetch是ES6中新增的方法,用来与服务器进行交流。
(1) fetch请求中的get方式
fetch(url).then(data=>data.json()).then(res=>{
console.log(res);
});
需要传递参数的情况下,可以在url中以"?"进行参数传递。如:url = “http://localhost:9000?id=3”。
(2) fetch请求中的post方式
fetch(url,{
method:"POST",
body:"向服务器传递的参数",
headers:{"Content-Type":"application/x-www-application/x-www-form-urlencoded"}
}).then(data=>data.json()).then(res=>{
console.log(res);
});
2.使用AJAX访问服务器
(1)Ajax无参的get请求
var xhr = new XMLHttpRequest();
xhr.open('GET',url);
xhr.send(null);
xhr.onreadystatechange = function(data){
if(this.readyState === 4){
console.log(data);
}
}
(2)Ajax有参的get请求
var xhr = new XMLHttpRequest();
xhr.open('GET',`${url}?id=1`);
xhr.send(null);
xhr.onreadystatechange = function(data){
if(this.readyState === 4){
console.log(data);
}
}
(3)Ajax无参的post请求
var xhr = new XMLHttpRequest();
xhr.open('POST',url);
xhr.send(null);
xhr.onreadystatechange = function(data){
if(this.readyState === 4){
console.log(data);
}
}
(4)Ajax有参的post请求
var xhr = new XMLHttpRequest();
xhr.open('POST',url);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencodex);
xhr.send("username=jacd&pwd=123");
xhr.onreadystatechange = function(data){
if(this.readyState === 4){
console.log(data);
}
}
3.使用jQuery的ajax方法
(1) $.ajax()
$.ajax({
url:url,
type:'post/get',
data:'Object/String/Array' ,//post请求时使用
dataType:'预期服务器返回的数据类型XML/HTML/JSON/Text',
success:function(result){} //请求成功后调用的函数
});
(2) $.get()
$.get(url,data,function(result){
console.log(result);
},“返回的格式xml,html,script,json,text,_default”);
(3) $.post()
$.post(url,data,callback(result){
console.log(result);
},"type:xml,html,script,json,text,_default");
//无参情况下get和post的data参数可以省略