以前整理的ajax相關應用筆記,一直沒有時間整理,今天忽然翻到特此將初稿大概的整理了一下,可能有點亂,歡迎指出不足之處。
javascript
jQuery的ajax請求:
complete函數通常不管服務器有無數據返回都會顯示(成功或者失敗都顯示數據):
return result
原生的Ajax請求:
// 原生ajax請求數據原理:
// var xhr = new XMLHttpRequest()
// 鏈接訪問地址
// xhr.open('GET','http://localhost:8000/shop/jsonApi')
// 設置一個監聽事件得狀態
// xhr.onreadystatechange = function(e){
// 判斷請求得狀態,達到下面條件便可拿到服務器返回得數據
// if(xhr.readyState == 4 && xhr.status==200){
// console.log(xhr)
// a=JSON.parse(xhr.responseText)
// console.log(a)
// 獲得返回得數據後,能夠在這裏進行dom操做渲染等
// }
//
// }
// xhr.send()
jQuery的Ajax請求仿axios(只是將$換成axios):
第一種方式:
此處爲get請求也能夠是post請求,參數一是請求的地址,參數二是請求時攜帶的數據data,then表示
請求成功後返回來的數據爲res,在該函數裏便可作對dom的一系列操做了,不過返回來的數據要通過json解析,由於在後端的時候數據被轉成json格式了
$.get('http://localhost:8000/shop/jsonApi',{'username':'admin','password':'admin'}).then(function(res){
console.log(res)
console.log(JSON.parse(res))
})
第二種方式:
參數一位請求的地址後面加一個?以後的都是用戶名和密碼是post的請求方式,這樣就能夠不用再寫data參數了,下面的和上面的第一種方式同樣。
$.get('http://localhost:8000/shop/jsonApi?username=admin&passoword=132345').then(function(res){
console.log(res)
console.log(JSON.parse(res))
})
vue裏前端渲染數據的方式:
<body>
<div id="app">
<h1>{{productname}}</h1>
<!--<div class="listItem" v-for='(item,index) in listArr' :key='index'>
<h1>{{item.title}}</h1>
<img :src="item.pic"/>
</div>-->
</div>
<script type="text/javascript">
var app = new Vue({
el:'#app',
data:{
productname:''
},
// mounted:function(){
// var that = this
// fetch('http://127.0.0.1:5000/rank/0').then(function(res){
// res.json().then(function(res){
// that.listArr = res.data.list
// console.log(res)
// })
// })
// }
mounted:function(){
var that = this
// 方式一:原生的fetch
// vue裏的fetch是一個ie6原生的可直接訪問數據,瀏覽器二次重寫方式
fetch('http://localhost:8000/shop/jsonApi').then(function(res){
// Promise對象是一個異步對象res.json()是一個Promise
console.log(res.json())
// 下面的纔是真正的返回的數據對象
res.json().then(function(res){
console.log(res)
})
// res.json().then(function(res){
//// that.listArr = res.data.list
// console.log(res)
// })
console.log(res)
})
}
})
// 方式二jQuery
// vue裏調用jQuery請求數據,並渲染頁面
$.get('http://localhost:8000/shop/jsonApi').then(function(res){
p = JSON.parse(res)
// 改變vue裏的productname的值而後渲染頁面
app.productname = p.name
})
</script>
</body>
django後端請求的數據路由及方法:http://localhost:8000/shop/jsonApi
路由:
在服務端設置可跨域請求條件:
import json
def jsonApi(request):
p1 = ProductModel.objects.get(pk=2)
dictObj = {
'name': p1.name,
'brief': p1.brief,
'productImg': str(p1.prodectImg),
'content': '<h1>圖片</h1>'
}
print(request.GET.get('username'))
# ensure_ascii設置中文不亂碼
jsonStr = json.dumps(dictObj,ensure_ascii=False)
# 設置可跨域請求得條件
result = HttpResponse(jsonStr)
result['Access-Control-Allow-Origin'] = '*'
result['Access-Control-Allow-Headers'] = "Content-Type"
django模式:步驟:在models.py創建class表---——》admin.py註冊表---——》views.py實例化表增刪改查,而後返回視圖---》urls.py設置views.py下每個不一樣方法的路由,便可
當post請求頁面出現下面報錯時:
的必須寫一個安全訪問參數到發送的數據裏: csrfmiddlewaretoken: '{{ csrf_token }}',爲固定用法,
function edit(e){
console.log(e)
console.log(e.target.dataset.eid)
}
function delt(e){
console.log(e)
var delid=e.target.dataset.did
console.log(e.target.dataset.did)
$.post('/houtai/lxl_delt/',{
'did':delid,
csrfmiddlewaretoken: '{{ csrf_token }}',
}).then(function(res){
console.log('tag', res)
})
}
function chaxun(e){
var product_name=$('.product_name').val()
var product_time=$('.product_time').val()
// console.log(product_name)
// console.log(product_time)
data={
'product_name':product_name,
'product_time':product_time,
headers:{'csrfmiddlewaretoken':'{{ csrf_token }}',},//標註請求頭,服務器才能安全讓其經過請求
}
$.ajax({
url:'/houtai/lxl_chaxun/',
type:'post',
data:data,
// headers:{'csrfmiddlewaretoken':'{{ csrf_token }}',},
success:function(res){
console.log(res)
// 後端返回路由,重定向路由,服務器再執行頁面渲染
location.href=''+res
}
})
}
ajax系列及跨域請求解決方案:
ajax:
後端返回數據:
前端:
後端解決跨域請求限制:
設置以後:
在服務端設置可跨域請求條件:
import json
def jsonApi(request):
p1 = ProductModel.objects.get(pk=2)
dictObj = {
'name': p1.name,
'brief': p1.brief,
'productImg': str(p1.prodectImg),
'content': '<h1>圖片</h1>'
}
print(request.GET.get('username'))
# ensure_ascii設置中文不亂碼
jsonStr = json.dumps(dictObj,ensure_ascii=False)
# 設置可跨域請求的條件
result = HttpResponse(jsonStr)
result['Access-Control-Allow-Origin'] = '*'
result['Access-Control-Allow-Headers'] = "Content-Type"
jQuery的ajax請求:
complete函數通常不管服務器有無數據返回都會顯示(成功或者失敗都顯示數據):
return result
原生的Ajax請求:
// 原生ajax請求數據原理:
// var xhr = new XMLHttpRequest()
// 鏈接訪問地址
// xhr.open('GET','http://localhost:8000/shop/jsonApi')
// 設置一個監聽事件得狀態
// xhr.onreadystatechange = function(e){
// 判斷請求得狀態,達到下面條件便可拿到服務器返回得數據
// if(xhr.readyState == 4 && xhr.status==200){
// console.log(xhr)
// a=JSON.parse(xhr.responseText)
// console.log(a)
// 獲得返回得數據後,能夠在這裏進行dom操做渲染等
// }
//
// }
// xhr.send()
2.axios數據傳輸:圖中選中的data部分要用{pramas:{‘username’:'admin','password':'admin'}}
線面被選中的是不一樣的傳輸數據的方式:
1,
vue數據交互:fetch方式瀏覽器二次重寫