zoukankan      html  css  js  c++  java
  • 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+"
    状态:"+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+"
    状态:"+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)})
    

    配置好路由后访问

  • 相关阅读:
    循环神经网络(LSTM和GRU)(1)
    threading包的例子和queue包的例子
    xgboost调参
    理解 Python 中的 *args 和 **kwargs
    TFRecords文件的生成和读取(1)
    tensorflow函数介绍(4)
    python其他篇(1)
    python实现Restful服务(基于flask)(2)
    开源多线程性能测试工具-sysbench
    MySQL 8.0.0 版本发布,亮点都在这了!
  • 原文地址:https://www.cnblogs.com/gcgc/p/9831669.html
Copyright © 2011-2022 走看看