Django学习之--Ajax

初识Ajax

Ajax并不是一门新的语言,它其实就是基于js写的一个功能模块而已

由于原生js书写ajax较为繁琐,django中我们一般直接使用jQuery封装好的ajax模块

1.1 ajax基本语法结构

 案例:

页面上有是三个input框,一个按钮,用户在前两个框中输入数字,点击按钮保证页面不刷新的情况下将数据发到后端做计算,再将计算好的结果发送给前端展示到第三个input框中

或:

 

1.2一直无法跳转到success函数中

 

 1.3 ajax提交json格式数据

参考文档:https://www.cnblogs.com/linkenpark/p/7461709.html

{% load static %}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>mysite测试</title>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
    <h1>加法计算:</h1>
    <input type="text" id="id1" name="第一个加数"/> +
    <input type="text" id="id2" name="第二个加数"/> =
    <input type="text" id="id3" name="和"/>
    <p></p>
    <input type="button" id="btn" value="提交" onclick="getusername()">

    <script>
        function getusername(){
            var id1 = $("#id1").val()
            var id2 = $("#id2").val()
            var data1 = {'id1':id1,'id2':id2}
            $.ajax({
                url: '/getinfo/',
                type: 'POST',
                data:{'data':JSON.stringify(data1)},
                dataType:"json",
                success: function(data){
                    console.log(data)
                    $("#id3").val(data)
                    }
            })
            }
    </script>
</body>
</html>
import json

from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import HttpResponseRedirect

# Create your views here.

def test(request):
    # return HttpResponse("hello world!")
    return render(request,'test.html')

def getinfo(request):
    data = request.POST.get('data')
    data = json.loads(data)
    print(data)
    print(type(data))
    id1 = data['id1']
    id2 = data['id2']
    id3 = int(id1)+int(id2)
    return HttpResponse(str(id3))

 

 请求参数:

原文地址:https://www.cnblogs.com/like1824/p/15355440.html