前端向服務器請求數據並渲染的方式(ajax/jQuery/axios/vue)


原理:

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))
//掛載后請求數據渲染頁面axios,data部分要用pramas參數,$也就是jQuery方式則不用添加這個參數
                mounted:function(){
                    axios.get('http://127.0.0.1:8000/axioApi/',{
                        //傳入后端的數據前要加一個參數params
                        params:{
                            'data':'nihao',
                            'mas':'keyi'
                        }
                        }).then(function(res){
                        console.log(res)
                    })
                }

 

        })
 注意: 當post請求頁面出現下面報錯時forbidden:
的必須寫一個安全訪問參數到發送的數據里: 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)
 })

}

 


第二種方式:
參數一位請求的地址后面加一個?之后的都是用戶名和密碼是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>
View Code

 


  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下每一個不同方法的路由,即可 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM