ajax
Posted 篓子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax相关的知识,希望对你有一定的参考价值。
jquery_ajax:
function ajaxClick1() {
$.ajax({
url:‘ajax1.html‘,
type:‘GET‘,
data:{‘p‘:123},
success:function (arg) {
console.log(arg)
}
})
}
原生ajax
GET请求:
function ajaxClick2() {
var xhr = new XMLHttpRequest(); //创建对象
xhr.onreadystatechange = function() { //模拟jquery回调函数
if (xhr.readyState){
console.log(xhr.responseText)
}
};
xhr.open(‘GET‘,‘/ajax1.html?p=123‘);
xhr.send(null);
}
django POST请求:
function ajaxClick4() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState){
console.log(xhr.responseText)
}
};
xhr.open(‘POST‘,‘/ajax1.html‘);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(‘p=123‘);
}
iframe仿造ajax请求
html:
<h3>iframe伪造ajax</h3>
<iframe name="ifra" id="iframe"></iframe>
<form id="fm" action="ajax1.html" method="post" target="ifra">
<input type="text" name="name">
<a onclick="ajaxClick5()">提交</a>
</form>
js:
function ajaxClick5() {
document.getElementById(‘iframe‘).onload = iframeClick;
document.getElementById(‘fm‘).submit();
}
function iframeClick() {
var ifr_load = this.contentWindow.document.body.innerHTML;
var obj = JSON.parse(ifr_load);
if (obj.status){
alert(obj.message)
}
}
jquery_ajax上传文件
function ajaxUpload() {
var data = new FormData(); 创建FROMDATA对象
data.append(‘k1‘,‘v1‘);
data.append(‘k2‘,‘v2‘);
data.append(‘k3‘,document.getElementById(‘files‘).files[0]);
$.ajax({
url:‘/ajax1.html‘,
type:‘POST‘,
data:data,
success:function (arg) {
console.log(arg);
},
processData:false,
contentType:false
})
}
原生ajax上传文件:
function ajaxUpload1() {
var data = new FormData();
data.append(‘k1‘,‘v1‘);
data.append(‘k2‘,‘v2‘);
data.append(‘k3‘,document.getElementById(‘files‘).files[0]);
var xhr = new XMLHttpRequest();
xhr.open(‘POST‘,‘/ajax1.html‘);
xhr.onreadystatechange = function () {
if (xhr.readyState){
console.log(xhr.responseText)
}
};
xhr.send(data);
}
django不通过FORM组件上传文件:
def ajax1(request):
data = {‘status‘:True,‘message‘:‘...‘}
print(request.GET)
print(request.POST)
file_name = request.FILES[‘k3‘]
with open(‘123‘,‘wb‘) as file:
for i in file_name.chunks():
file.write(i)
import json
return HttpResponse(json.dumps(data))
以上是关于ajax的主要内容,如果未能解决你的问题,请参考以下文章