码迷,mamicode.com
首页 > Web开发 > 详细

django使用ajax传输数据

时间:2018-10-22 20:40:04      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:image   unicode   UNC   签名   charset   button   djang   json   har   

 

 

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传输数据

标签:image   unicode   UNC   签名   charset   button   djang   json   har   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!