关于ajax及相关数据传输问题

之前整理的ajax相关应用笔记,一直没有时间整理,今天突然翻到特此将初稿大概的整理了一下,可能有点乱,欢迎指出不足之处。

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方式浏览器二次重写
 
 
 
posted @ 2018-12-02 16:47  L某人  阅读(236)  评论(0编辑  收藏  举报