首页 > 代码库 > Ajax-05 使用XMLHttpRequest和jQuery实现Ajax实例

Ajax-05 使用XMLHttpRequest和jQuery实现Ajax实例

需求:

(django)使用XMLHttpRequest和jQuery实现Ajax加法运算

 

url.py:

from django.conf.urls import url
from hello import views

urlpatterns = [
    url(radd/, views.add, name=add),
    url(radd_number/, views.add_number, name=add_number),

]

add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>XMLHttpRequest-Ajax请求</h1>
<input type="button" onclick="XmlRequest();" value="发送请求">

<h1>jQuery-Ajax请求</h1>
<input type="button" onclick="JqRequest();" value="发送请求">

<script src="http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
    function XmlRequest() {
        var xhr = new XMLHttpRequest();
        // 定义回调函数
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                //已经接收到全部响应数据,执行以下操作
                var data = xhr.responseText;
                console.log(data);
            }
        };
        // 指定连接方式和地址--文件方式
        xhr.open(POST, {% url add_number %}, true);
        // 设置请求头
        xhr.setRequestHeader(Content-Type, application/x-www-form-urlencoded;charset=UTF-8);
        // 发送请求
        xhr.send(n1=2;n2=4;);
    }

    function JqRequest() {
        $.post({
            url: {% url add_number %},
            data: {"n1": 222, "n2": 444},
            dataType: text,
            success: function (data, statusText, xmlHttpRequest) {
                console.log(data);
            }
        });

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

views.py

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt


def add(request):
    return render(request, add.html)

@csrf_exempt
def add_number(request):
    method = request.method
    n1 = request.POST.get(n1)
    n2 = request.POST.get(n2)
    result = int(n1) + int(n2)

    content = {"method":%s,"result":%s} % (method, result)
    return HttpResponse(content)

测试结果如:

技术分享

 

Ajax-05 使用XMLHttpRequest和jQuery实现Ajax实例