使用AJAX与Django通信

这里使用原生JavaScript通过 XMLHttpRequest 对象向django发送Ajax请求提交表单数据,并处理响应。

一,HTML页面

<!DOCTYPE html>
<html lang="en">
	<head>
	    <title>XHR Post Example</title>
	</head>
	<body>
		<p>Fill in the form below:</p>
		<form id="user-info">
		    <label for="user-name">Name:</label><input type="text" id="user-name" name="user-name"/><br/>
		    <label for="user-email">Email:</label><input type="text" id="user-email" name="user-email"/><br/>
		    <input type="button" value="Submit" onclick="submitData()"/>
		</form>
		<div id="myDiv"></div>
	</body>
</html>

二,JavaScript代码

<script type="text/javascript">
    function createXHR() {
        if (typeof XMLHttpRequest != "undefined") {
            return new XMLHttpRequest();
        } else if (typeof ActiveXObject != "undefined") {
            if (typeof arguments.callee.activeXString != "string") {
                var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0",
                    "MSXML2.XMLHttp"], i, len;

                for (i = 0, len = versions.length; i < len; i++) {
                    try {
                        var xhr = new ActiveXObject(versions[i]);
                        arguments.callee.activeXString = versions[i];
                        return xhr;
                    } catch (ex) {
                        //skip
                    }
                }
            }

            return new ActiveXObject(arguments.callee.activeXString);
        } else {
            throw new Error("No XHR object available.");
        }
    }

    function serialize(form) {
        var parts = [];
        var field = null;

        for (var i = 0, len = form.elements.length; i < len; i++) {
            field = form.elements[i];

            switch (field.type) {
                case "select-one":
                case "select-multiple":
                    for (var j = 0, optLen = field.options.length; j < optLen; j++) {
                        var option = field.options[j];
                        if (option.selected) {
                            var optValue = "";
                            if (option.hasAttribute) {
                                optValue = (option.hasAttribute("value") ?
                                    option.value : option.text);
                            } else {
                                optValue = (option.attributes["value"].specified ?
                                    option.value : option.text);
                            }
                            parts.push(encodeURIComponent(field.name) + "=" +
                                encodeURIComponent(optValue));
                        }
                    }
                    break;

                case undefined:     //fieldset
                case "file":        //file input
                case "submit":      //submit button
                case "reset":       //reset button
                case "button":      //custom button
                    break;

                case "radio":       //radio button
                case "checkbox":    //checkbox
                    if (!field.checked) {
                        break;
                    }
                /* falls through */

                default:
                    parts.push(encodeURIComponent(field.name) + "=" +
                        encodeURIComponent(field.value));
            }
        }
        return parts.join("&");
    }

    function submitData() {
        const xhr = createXHR();
        xhr.onreadystatechange = function (event) {
            if (xhr.readyState === 4) {
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
                    const data = JSON.parse(xhr.responseText);
                    console.log(typeof data);
                    console.log(data);
                    const element = document.getElementById("myDiv");
                    element.innerHTML = data['user-name']+" "+data['user-email'];
                } else {
                    alert("Request was unsuccessful: " + xhr.status);
                }
            }
        }
        xhr.open("POST", "/post/", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        var form = document.getElementById("user-info");
        xhr.send(serialize(form));
    }
</script>

三,django视图函数

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

@csrf_exempt
def index(request):
    if request.method == 'POST':
        print(request.body) # b'user-name=1&user-email=1%40q.com'
        data = {}
        name = request.POST.get('user-name', '')
        email = request.POST.get('user-email', '')
        data['user-name'] = name
        data['user-email'] = email
        data = json.dumps(data)
        print(data)
        print(type(data))
        return HttpResponse(data, content_type="application/json")
    return render(request, 'index.html', locals())

四,django URL

urlpatterns = [
    path('admin/', admin.site.urls),
    path('post/', index, name="post"),
]

整个过程:

  1. 访问http://127.0.0.1:8000/post/,填写表单。
  2. 使用 XMLHttpRequest 对象实现Ajax请求,POST提交序列化的表单数据。
  3. django解析请求数据,简单处理后返回所有表单数据。
  4. JavaScript接收响应,局部刷新并显示数据。

之前有篇文章 django:一个简单的Ajax无刷计算器非常简单地使用了jQuery Ajax实现与django的数据交互。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值