JavaScript 伪Ajax请求

伪Ajax

   通过iframe以及form表单,可以实现伪Ajax的方式。

   并且它的兼容性是最好的。

iframe

   iframe标签能够获取一个其他页面的文档内容,这说明它内部肯定是发送了一个请求,并且收到后端的数据展示在页面上。

   基于这一点,我们可以让他与form表单做一个结合使用。

<iframe src="//www.baidu.com//" frameborder="0"></iframe>

   image-20200915180122795

结合使用

   首先form表单中有一个target属性,我们需要为iframe取一个名字。并且让target属性与iframe做绑定。

   至于提交方式与提交的数据,均是form表单中的内容。

   注意:如果要上传文件,一定要指定enctypemultipart/form-data,否则后端Django不会将文件存放进request.FILES中。

<iframe name="ajax"></iframe>
<form action="//127.0.0.1:8000/" method="POST" target="ajax" enctype="multipart/form-data" >
        <p><input type="text" name="username"></p>
        <p><input type="text" name="password"></p>
        <p><input type="file" name="userfile"></p>
        <p><button type="submit">提交</button></p>
</form>
def test(request):
    if request.method == "POST":
        print(request.POST) # <QueryDict: {'username': ['Yunya'], 'password': ['123']}>
        print(request.FILES)  # <MultiValueDict: {'userfile': [<InMemoryUploadedFile: django-orm单表练习.gif (image/gif)>]}>
        return HttpResponse("ok")
    else:
        print(request.GET)
        return render(request,"base.html",locals())

回调函数

   现在我们需要为iframe绑定一个回调函数,当iframe中有内容时则取出来。

   同时我们还要让iframe的高度为0,让页面感知不到我们是在用伪Ajax在发送请求。

<body>
    
<iframe name="ajax" style="display: none;"></iframe>
    <form action="//127.0.0.1:8000/" method="POST" target="ajax" enctype="multipart/form-data" >
        <p><input type="text" name="username"></p>
        <p><input type="text" name="password"></p>
        <p><input type="file" name="userfile"></p>
        <p><button type="submit">提交</button></p>
    </form>

</body>

<script>
    window.onload = () => {
     
        document.getElementsByName("ajax")[0].addEventListener("load",function(ele){
            let result = this.contentWindow.document.body.innerHTML;  // 获取iframe中的内容
             console.log(result);

        })

    }
</script>
def test(request):
    if request.method == "POST":
        print(request.POST) # <QueryDict: {'username': ['Yunya'], 'password': ['123']}>
        print(request.FILES)  # <MultiValueDict: {'userfile': [<InMemoryUploadedFile: django-orm单表练习.gif (image/gif)>]}>
        return HttpResponse("ok")
    else:
        print(request.GET)
        return render(request,"base.html",locals())

   伪造Ajax

后期思路

   你可以在后面围绕上面知识点做一个组件。我这里就懒得写了,具体思路如下:

   1.使用Js创建出iframe标签,以及form表单,但是不向body中进行添加。

   2.根据参数,来选定form中的enctype

   3.根据提交的数据长度,来生成input框在form表单中,并且生成对应的namevalue

   4.根据参数,来设定form中的method以及action属性。

   5.自己做一个回调函数