django使用ajax传输数据

HTML文件ajax get例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax get</title>
    {#必须先引入jQuery库#}
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    {# jQuery ajax get 请求练习  #}
    <script>
        $(document).ready(function () {
            $("#test").click(function () {   //用id或者标签名都可以
            {#$("button").click(function () {#}
                $.get("/jQuery_get/",function () {
                    {#alert("hhah");#}
                    res = {{ res|safe}}; //从后台传过来的数据,必须放在这里面
                    console.log(res.data); //为什么没有打印出来
                    alert("数据:"+res.data+"\n状态:"+res.status);
                });
            });
        });
    </script>
</head>
<body>
<button id="test">测试发送一个jQuery的ajax get请求,并获取返回结果</button>
</body>
</html>

  

HTML文件ajax post例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax post</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(function () {
            $("button").click(function () {
                $.ajax({
                    type:"POST",
                    url:"/jQuery_post/",
                    {#加上这个传入数据不能显示alert#}
                    {#data:{'name':naddme},#}
                    {#dataType:"json",#}
                    success:function () {
                        res = {{ res|safe }}; //从后台获取的数据
                        {#alert("hahha")#}
                        alert("数据:"+res.data+"\n状态:"+res.status)
                    }
                });
            });
        });
    </script>
</head>
<body>
<button id="test">post请求</button>
</body>
</html>

  

Django后台view文件

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.shortcuts import render


def jQuery_get(request):
    res = {"data": "这是后台返回的数据","status": "true"}
    #  向js中传递数据必须json.dumps()处理
    return render(request, 'jQuery_get.html', {'res': json.dumps(res)})

def jQuery_post(request):
    res = {"data": "这是post请求后,后台返回的数据","status": "true"}
    #  向js中传递数据必须json.dumps()处理
    return render(request, 'jQuery_post.html', {'res': json.dumps(res)})

配置好路由后访问

猜你喜欢

转载自www.cnblogs.com/gcgc/p/9831669.html
今日推荐