Ajax JavaScript传参-javascript加载本地文件

 

get请求需要拼接到url里面

 

post请求,需要放到send方法里面,后端取值的时候,Ajax用JavaScript传输跟用postman传输,取值方式有些区别,这里做一下详细记录

传参格式{'id':1}
        request.body取值,得到的结果如下:
        b'{\r\n    "name":"olive",\r\n    "phone":18503234424,\r\n    "home":"\xe6\xb1\x9f\xe8\x8b\x8f\xe7\x9c\x81"\r\n}' <class 'bytes'>
        ajax post body params b'{"name":"kevin","phone":"13689897878","home":"\xe5\x90\x89\xe6\x9e\x97\xe7\x9c\x81"}' <class 'bytes'>
        
        request.data取值,postman 和ajax 反馈结果如下:
        ajax  <QueryDict: {'{"name":"simon","phone":"15646465585","home":"安徽省"}': ['']}> <class 'django.http.request.QueryDict'>
        postman   {'data': {'name': 'oven', 'phone': 18503004424, 'home': '江苏省'}} <class 'dict'>

后端是用APIView,post取值方式,request.data/request.body
当用request.body取值的时候,不论是postman还是Ajax都是byte格式,拿到byte之后,json.loads就能得到对象,可以直接拿到数据。
用request.data取值的时候,Ajax传过来的就是querydict,postman传过来的就是dict对象。这个还挺奇怪的。可能是request里面封装了什么东西导致的这样的区别

 

传参格式   data={‘id’:1}
当传参格式发生变化时,request.data取值,ajax传递的querydict格式发生变化,如下
<QueryDict: {'data': ['{"name":"simon","phone":"15646465585","home":"安徽省"}']}> <class 'django.http.request.QueryDict'>

request.data.get("data") 拿到的是str需要序列化转成dict对象

 

javascript加载本地文件

function readTextFile(file, callback) {
// file是本地文件路径 let rawFile
= new XMLHttpRequest(); rawFile.overrideMimeType("application/json"); rawFile.open("GET", file, true); rawFile.responseType = 'json'; //在onreadystatechange之前,设置返回值类型, // 就会自动解析为json数据格式 rawFile.onreadystatechange = function () { if (rawFile.readyState === 4 && rawFile.status === 200) { let response_data = rawFile.response; console.log("lmj-debug>>>", response_data); callback(response_data); } }; rawFile.send(null); }

 

posted @ 2021-04-30 15:11  dream-子皿  阅读(160)  评论(0编辑  收藏  举报