首页 > Web开发 > 详细

django使用ajax传输数据

时间:2018-10-22 18:34:21      阅读:449      评论:0      收藏:0      [点我收藏+]

 

 

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)})

 

配置好路由后访问

技术分享图片

 

技术分享图片

 

django使用ajax传输数据

原文:https://www.cnblogs.com/gcgc/p/9831669.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!