目錄
一、jQuery 方式
1. $.get() 獲取資料
① $.get() 發起不帶引數的請求
② $.get() 發起帶引數的請求
2. $.post() 提交資料
$.post() 向服務器提交資料
3. $.ajax() 既可以獲取也可以提交資料
① 使用 $.ajax() 發起 GET 請求(只需要將 type 屬性設定為' GET '即可)
② 使用 $.ajax() 發起 POST 請求
二、xhr 方式
1. 使用 xhr 發起 GET 請求
2. 使用 xhr 發起 POST 請求
三、axios 方式
1. 使用 axios 發起 GET 請求
2. 使用 axios 發起 POST 請求
3. 直接使用 axios 發起請求
① 直接使用 axios 發起 GET 請求
② 直接使用 axios 發起 POST 請求
今天分享的內容都是資料互動中的重中之重,滿滿的干貨,一定要仔細看噢~
一、jQuery 方式
瀏覽器中提供的XMLHttpRequest用法比較復雜,所以jQuery對XMLHttpRequest進行了封裝,提供了一系列Ajax相關的函式,極大地降低了Ajax的使用難度,
jQuery 中發起 Ajax 請求最常用的三個方法如下:
1. $.get() 獲取資料
$.get(url,[data],[callback])
引數名 引數型別 是否必選 說明 url string 是 要請求的資源地址 data object 否 請求資源期間要攜帶的引數 callback function 否 請求成功時的回呼函式
① $.get() 發起不帶引數的請求
$.get('http://www.liulongbin.top:3006/api/getbooks',function(res){
console.log(res) // 這里的 res 是服務器回傳的資料
})
② $.get() 發起帶引數的請求
$.get('http://www.liulongbin.top:3006/api/getbooks', { id: 1 }, function(res){
console.log(res)
})
切記!!!其中引數是以物件的形式
2. $.post() 提交資料
$.post(url,[data],[callback])
引數名 引數型別 是否必選 說明 url string 是 提交資料的地址 data object 否 要提交的資料 callback function 否 資料提交成功時的回呼函式
$.post() 向服務器提交資料
$.post(
'http://www.liulongbin.top:3006/api/addbook', //請求的 URL 地址
{ bookname: '水滸傳', author: '施耐庵', publisher: '上海圖書出版社'}, //提交的資料
function(res) { // 回呼函式
console.log(res)
}
)
3. $.ajax() 既可以獲取也可以提交資料
$.ajax({
type: ' ', // 請求的方式,例如 GET 或 POST
url: ' ', // 請求的 URL 地址
data: { }, // 這次請求要攜帶的資料
success: function(res) { } // 請求成功之后的回呼函式
})
① 使用 $.ajax() 發起 GET 請求(只需要將 type 屬性設定為' GET '即可)
$.ajax({
type: 'get',
url: 'http://www.liulongbin.top:3006/api/getbooks',
data: { id: 1 }
success: function(res) {
console.log(res)
}
})
② 使用 $.ajax() 發起 POST 請求
$.ajax({
type: 'post',
url: 'http://www.liulongbin.top:3006/api/getbooks',
data: {
bookname: '水滸傳',
author: '施耐庵',
publisher: '上海圖書出版社'
},
success: function(res) {
console.log(res)
}
})
既然了解了概念,那我們就實操一下,下面看個例題:實作圖書串列的增刪顯示功能
實作效果如下:

實作代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="bootstrap.css">
<script src="jQuery.min.js"></script>
</head>
<body style="padding: 15px">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">添加新圖書</h3>
</div>
<div class="panel-body form-inline">
<div class="input-group">
<div class="input-group-addon">書名</div>
<input type="text" class="form-control" id="iptBookname" placeholder="請輸入書名">
</div>
<div class="input-group">
<div class="input-group-addon">作者</div>
<input type="text" class="form-control" id="iptAuthor" placeholder="請輸入作者">
</div>
<div class="input-group">
<div class="input-group-addon">出版社</div>
<input type="text" class="form-control" id="iptPublisher" placeholder="請輸入出版社">
</div>
<button id="btn" class="btn btn-primary">添加</button>
</div>
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>書名</th>
<th>作者</th>
<th>出版社</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tb">
</tbody>
</table>
<script>
$(function(){
//獲取圖書串列資料
function getBookList(){
$.get('http://www.liulongbin.top:3006/api/getbooks',function(res){
if(res.status !== 200) return alert('獲取資料失敗!');
// 把獲取到的資料都存放在陣列中
var rows = []
$.each(res.data, function(i,item){
rows.push('<tr><td>'+item.id+'</td><td>'+item.bookname+'</td><td>'+item.author+'</td><td>'+item.publisher+'</td><td><a href:"javascript:;" class="del" data-id="'+item.id+'">洗掉</a></td></tr>')
})
// 將陣列轉化為字串渲染到頁面
$('#tb').empty().append(rows.join(''))
})
}
getBookList()
//洗掉圖書
$('tbody').on('click','.del',function(){
var id = $(this).attr('data-id')
$.get('http://www.liulongbin.top:3006/api/delbook',{id: id},function(res){
if(res.status !== 200) return alert('洗掉圖書失敗!')
// 呼叫該函式,把頁面重新渲染一遍
getBookList()
})
})
$('#btn').on('click',function(){
// trim() 函式可以去除字串兩端的空格
var bookname = $('#iptBookname').val().trim()
var author = $('#iptAuthor').val().trim()
var publisher = $('#iptPublisher').val().trim()
if(bookname.length <= 0 || author.length <=0 || publisher.length <=0) {
return alert('請填寫完整的圖書資訊!')
}
// 添加圖書
$.post('http://www.liulongbin.top:3006/api/addbook',{bookname: bookname, author: author,publisher: publisher},function(res){
if(res.status !== 201) return alert('添加圖書失敗!')
getBookList()
// 清空輸入框內容
$('#iptBookname').val('')
$('#iptAuthor').val('')
$('#iptPublisher').val('')
})
})
})
</script>
</body>
</html>
二、xhr 方式
XMLHttpRequest(簡稱 xhr) 是瀏覽器提供的 Javascript 物件,通過它,可以 請求服務器上的資料資源. 之前所學的 jQuery 中的 Ajax 函式,就是基于 xhr 物件封裝出來的
1. 使用 xhr 發起 GET 請求
方法如下圖所示:
// 1. 創建 xhr 物件
var xhr = new XMLHttpRequest()
// 2. 呼叫 open 函式,指定 請求方式 與 URL地址
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks')
// 3. 呼叫 send 函式,發起 Ajax 請求
xhr.send()
// 4. 監聽 onreadystatechange 事件
xhr.onreadystatechange = function() {
// 4.1 監聽 xhr 物件的請求狀態 readyState; 與服務器回應的狀態 status
if(xhr.readyState === 4 && xhr.status === 200) {
// 4.2 列印服務器回應回來的資料
console.log(xhr.responseText);
}
}
如果發起的是帶引數的 GET 請求,只需要在呼叫 xhr.open 期間,為 URL 地址指定引數即可:
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks?id=1&bookname=西游記')
多個引數之間用 & 連接
2. 使用 xhr 發起 POST 請求
方法如下圖所示:
// 1. 創建 xhr 物件
var xhr = new XMLHttpRequest()
// 2. 呼叫 open 函式,指定 請求方式 與 URL地址
xhr.open('POST','http://www.liulongbin.top:3006/api/addbooks')
// 3. 設定 Content-Type 屬性(固定寫法)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
// 4. 呼叫 send 函式,同時將資料以 查詢字串 的形式,提交給服務器
xhr.send('bookname=水滸傳&author=施耐庵&publisher=天津圖書出版社')
// 5. 監聽 onreadystatechange 事件
xhr.onreadystatechange = function() {
// 4.1 監聽 xhr 物件的請求狀態 readyState; 與服務器回應的狀態 status
if(xhr.readyState === 4 && xhr.status === 200) {
// 4.2 列印服務器回應回來的資料
console.log(xhr.responseText);
}
}
以 xhr 方式發起 PSOT 和 GET 請求的區別:
① 傳遞資料引數的位置不同:GET 方式是寫在 URL 地址的后面,而 POST 方式是寫在xhr.send() 中
② 發起 POST 請求時,必須寫 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded') ,GET 請求不需要寫
三、axios 方式
Axios 是專注于網路資料請求的庫,相比于原生的 XMLHttpRequest 物件, axios 簡單易用. 相比于 jQuery,axios 更加輕量化,只專注于網路資料請求
使用前要先匯入 axios.js 包
1. 使用 axios 發起 GET 請求
語法:
axios.get('url', { params: { /*引數*/} }).then(callback)
代碼如下:
// 請求 URL 地址
var url = 'http://www.liulongbin.top:3006/api/get'
// 請求的引數物件
var paramsObj = { name: 'zs', age: 20 }
// 呼叫 axios.get() 發起 GET 請求
axios.get(url, { params: paramsObj }).then(function(res){
// res.data 是服務器回傳的資料
var result = res.data
console.log(res);
})
2. 使用 axios 發起 POST 請求
語法:
axios.post('url', { /*引數*/} ).then(callback)
代碼如下:
// 請求 URL 地址
var url = 'http://www.liulongbin.top:3006/api/post'
// 要提交到服務器的資料
var dataObj = { location: '北京', address: '順義' }
// 呼叫 axios.post() 發起 POST 請求
axios.post(url, dataObj).then(function(res){
// res.data 是服務器回傳的資料
var result = res.data
console.log(res);
})
axios 發起 GET 和 POST 語法的區別:
GET 請求時,引數要通過 params 屬性提供,而 POST 不用
3. 直接使用 axios 發起請求
axios 也提供了類似于 jQuery 中 $.ajax() 的函式,語法如下:
axios({
method: '請求型別',
url: '請求的URL地址'
data: { /* POST資料 */},
params: { /* GET引數 */}
}).then(callback)
① 直接使用 axios 發起 GET 請求
axios({
method: 'GET',
url: 'http://www.liulongbin.top:3006/api/get',
params: { // GET 引數要通過 params 屬性提供
name: 'zs',
age: 20
}
}).then(function(res){
console.log(res.data);
})
② 直接使用 axios 發起 POST 請求
axios({
method: 'POST',
url: 'http://www.liulongbin.top:3006/api/post',
data: { // POST 引數要通過 data 屬性提供
bookname: '程式員的自我修養',
price: 666
}
}).then(function(res){
console.log(res.data);
})
案例實踐:使用 axios 發起 GET 和 POST 請求獲取資料,并渲染到頁面
實作效果:

實作代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./axios.js"></script>
<style>
body {
padding-left: 50px;
}
.container {
width: 300px;
height: 150px;
box-shadow: 0 0 5px rgba(0,0,0,0.8);
background-color: #c7c7c7;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container">
</div>
<button id="btn1">get更換</button>
<button id="btn2">post更換</button>
<script>
document.querySelector('#btn1').addEventListener('click',function(){
var url = 'https://xl.xilinglaoshi.com:8001/fenshou'
axios({
method: 'GET',
url: url,
}).then(function(res){
// 獲取到需要的資料并渲染到頁面
document.querySelector('.container').innerHTML = res.data.data[0].content;
})
})
document.querySelector('#btn2').addEventListener('click',function(){
var url = 'https://xl.xilinglaoshi.com:8001/qingshi'
axios({
method:'POST',
url: url,
}).then(function(res){
document.querySelector('.container').innerHTML = res.data.data[0].content;
})
})
</script>
</body>
</html>
這次的分享到這就結束啦~希望可以收到你的小心心~

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/354655.html
標籤:其他
上一篇:EDG奪冠,Python分析一波B站評論,總結:EDG,nb
下一篇:教你從零開始畫echarts地圖
