前端向服务器请求数据并渲染的方式(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>
 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"

 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号