AJAX入门学习-2:基于JS的AJAX实现(以Django为例)

栏目: Python · 发布时间: 7年前

内容简介:小生博客:如果有疑问,请点击此处,然后发表评论交流,作者会及时回复。一. ajax的实现操作流程

小生博客: http://xsboke.blog.51cto.com

如果有疑问,请点击此处,然后发表评论交流,作者会及时回复。

-------谢谢您的参考,如有疑问,欢迎交流

一. ajax的实现操作流程

实例对象:
                var xmlhttp = XMLHttprequest() 

        连接server端:
                xmlhttp.open("")

        发送数据:
                xmlhttp.send("")        # 请求体的内容    ,如果是GET请求就没有内容,内容在URL里面,写为send(null)

        监听:
                xmlhttp(if == 4:{var context = xmlhttp.responsetext})  # 判断服务器是否响应结束,其中4状态表示服务器响应结束

二. ajax第一样例,发送get请求

2.1 django的urls.py

from django.contrib import admin
        from django.urls import path
        from django.conf.urls import url
        from ajax import views

        urlpatterns = [
            path('admin/', admin.site.urls),
            url(r'^index',views.index),
            url(r'ajax_receive',views.ajax_receive),
        ]

2.2 django的views.py

from django.shortcuts import render,HttpResponse

        # Create your views here.

        def index(req):
            return  render(req,"index.html")

        def ajax_receive(req):
            return  HttpResponse("hello")

2.3 模板文件 index.html

<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
        </head>
        <body>
        <button onclick="func1();">ajax提交</button>

        <script>
            // 生成一个xml对象
            function createXMLHttpRequest() {
                var xmlHttp;
                // 适用于大多数浏览器,以及IE7和IE更高版本
                try {
                    xmlHttp = new XMLHttpRequest();
                } catch (e) {
                    //适用于IE6
                    try {
                        xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
                    } catch (e) {
                        //适用于IE5.5,以及IE更早版本
                        try {
                            xmlHttp = new ActiveXObject(("Microsoft.XMLHTTP"));
                        } catch (e) {}
                    }
                }
                return xmlHttp;
            }

            // 实例化对象,打开连接,发送数据,返回数据
            function func1 () {
                //step1
                var xmlhttp = createXMLHttpRequest()        // 实例对象

                //step2
                xmlhttp.open("GET","/ajax_receive",true)    // 参数1:请求方式;参数二:请求接口;参数三:采用异步

                //step3
                xmlhttp.send(null);     // 发送数据

                //step4
                xmlhttp.onreadystatechange=function () {
                    if ( xmlhttp.readyState == 4 && xmlhttp.status == 200){
                        // alert(xmlhttp.status)     //返回HTTP码状态
                        // alert(xmlhttp.readyState) //返服务器响应状态,4位响应结束

                        var data = xmlhttp.responseText
                        alert(data)
                    }
                }
            }

        </script>
        </body>
        </html>

三. ajax第二样例,发送post请求

3.1 django的urls.py

from django.contrib import admin
        from django.urls import path
        from django.conf.urls import url
        from ajax import views

        urlpatterns = [
            path('admin/', admin.site.urls),
            url(r'^index',views.index),
            url(r'ajax_receive',views.ajax_receive),
        ]

3.2 django的views.py

from django.shortcuts import render,HttpResponse

        # Create your views here.

        def index(req):
            return  render(req,"index.html")

        def ajax_receive(req):
            if req.method == "POST":
                print("req.POST",req.POST)

            return  HttpResponse("hello2")

3.3 模板文件 index.html

<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
        </head>
        <body>
        <button onclick="func1();">ajax提交</button>

        <!-- ajax和form都是和后端进行数据交互的,form的enctype和ajax设置请求头是一个道理,
        但是form是默认就有这个请求头的,所以我们在写form的时候不用特意指定请求头 -->
        <form action="//" method="post" enctype="application/x-www-form-urlencoded">
            <input type="text">
            <input type="text">
        </form>
        <script>
            // 生成一个xml对象
            function createXMLHttpRequest() {
                var xmlHttp;
                // 适用于大多数浏览器,以及IE7和IE更高版本
                try {
                    xmlHttp = new XMLHttpRequest();
                } catch (e) {
                    //适用于IE6
                    try {
                        xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
                    } catch (e) {
                        //适用于IE5.5,以及IE更早版本
                        try {
                            xmlHttp = new ActiveXObject(("Microsoft.XMLHTTP"));
                        } catch (e) {}
                    }
                }
                return xmlHttp;
            }

            // 实例化对象,打开连接,发送数据,返回数据
            function func1 () {
                //step1
                var xmlhttp = createXMLHttpRequest();        // 实例对象

                //step2
                xmlhttp.open("POST","/ajax_receive",true);    // 参数1:请求方式;参数二:请求接口;参数三:采用异步

                // POST方法需要设置一个请求头,如果不设置请求头,Web容器会忽略请求体的内容
                // POST方法需要设置请求头,是因为要提交的数据需要放在请求体里面
                // GET方法不需要是因为GET提交的主体是空的
                // 必须放在send之前,open之后,固定的POST参数
                xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

                //step3
                // xmlhttp.send(null);     // 发送数据
                xmlhttp.send("name=dashan");  //POST向后台提交数据

                //step4
                xmlhttp.onreadystatechange=function () {
                    if ( xmlhttp.readyState == 4 && xmlhttp.status == 200){
                        // alert(xmlhttp.status)     //返回HTTP码状态
                        // alert(xmlhttp.readyState) //返服务器响应状态,4位响应结束

                        var data = xmlhttp.responseText;
                        alert(data)
                    }
                }
            }

        </script>
        </body>
        </html>

3.4 GET与POST的不同

3.4.1 open方法改为了POST
        3.4.2 需要提交的数据写到send里面
        3.4.3 因为POST的Request体是有数据的,所以必须设置请求头

四. AJAX第三例(实现用户名是否已注册)

4.1 功能介绍

在注册表单中,当用户填写了用户名后,把光标移开,会自动向服务器发送异步请求,服务器返回TRUE或False,
        返回true表示这个用户已经被注册过,返回false表示没有注册过

        客户端得到服务器返回的结果后,确定是否在用户名文本框后显示"用户名已被注册"的错误信息!

4.2 案例分析

- 页面中给出注册表单
        - 在username表单字段中添加onblur事件,调用send()方法
        - send()方法获取username表单字段的内容,向服务器发送异步请求,参数为username
        - django的视图函数:获取username参数,判断是否为"yuan",如果是响应true,否则响应false

4.3 代码

4.3.1 django的urls.py

from django.contrib import admin
            from django.urls import path
            from django.conf.urls import url
            from ajax import views

            urlpatterns = [
                path('admin/', admin.site.urls),
                url(r'ajax_register',views.ajax_register),
            ]

4.3.2 django的views.py

from django.shortcuts import render,HttpResponse

            # Create your views here.

            def ajax_register(req):

                if req.method == "POST":
                    username = req.POST.get("username")

                    if username == "dashan":
                        return HttpResponse("true")

                    return HttpResponse("false")

                return render(req,"register.html")

4.3.3 模板文件 register.html

<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>Title</title>
            </head>
            <body>
            <form>
                <p>用户名:<input type="text" name="username" onblur="func1(this);"></p>
                <span id="error"></span>
                <p>密码:<input type="password" name="passwd"></p>
                <input type="submit" value="提交">
            </form>

            <script>

                function createXMLHttpRequest() {
                    var xmlHttp;
                    // 适用于大多数浏览器,以及IE7和IE更高版本
                    try {
                        xmlHttp = new XMLHttpRequest();
                    } catch (e) {
                        //适用于IE6
                        try {
                            xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
                        } catch (e) {
                            //适用于IE5.5,以及IE更早版本
                            try {
                                xmlHttp = new ActiveXObject(("Microsoft.XMLHTTP"));
                            } catch (e) {}
                        }
                    }
                    return xmlHttp;
                }

                function func1(self) {
                    var username = self.value;

                    var xmlhttp = createXMLHttpRequest();
                    xmlhttp.open("POST","/ajax_register",true);
                    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

                    xmlhttp.send("username="+username);  // 如果是变量的话,必须这样写,等于号在双引号里面

                    xmlhttp.onreadystatechange=function(){
                        if(xmlhttp.readyState==4 && xmlhttp.status==200){

                            var s = xmlhttp.responseText
                            if (s == "true"){
                                document.getElementById("error").innerHTML="用户名已存在"
                            }
                        }

                    }
                }
            </script>
            </body>
            </html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Everything Store

The Everything Store

Brad Stone / Little, Brown and Company / 2013-10-22 / USD 28.00

The definitive story of Amazon.com, one of the most successful companies in the world, and of its driven, brilliant founder, Jeff Bezos. Amazon.com started off delivering books through the mail. Bu......一起来看看 《The Everything Store》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具