美文网首页
jQuery使用Ajax

jQuery使用Ajax

作者: 山坡上的斐德洛 | 来源:发表于2018-11-24 21:44 被阅读0次

使用django做后台,通过jQuery调用Ajax,偷偷的向后台发数据。

  1. 首先,下载好jQuery,我的jQuery文件放在根目录下的static/JS文件夹下。
  2. 在前端中,写好两个输入框和一个提交按钮,以及script脚本
{% load staticfiles %}
<!DOCTYPE>
<html >
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
        <title></title>
        <style type="text/css">
            .btn{
                display: inline-block;
                padding: 5px 15px;
                background-color: #6eb6de;
                color: white;
                {#调整鼠标的形状#}
                cursor: pointer;
            }
        </style>

    </head>
    <body>
    <div>

        <input placeholder="用户名" type="text" id="username">
        <input placeholder="密码" type="password" id="password">
        <div class="btn" onclick="submitForm()">提交</div>
    </div>

    <script src="/static/JS/jquery.js"></script>
    <script>
        function submitForm() {
            var u = $('#username').val();
            var p = $('#password').val();
            $.ajax({
                url: '/test2',
                type: "GET",
                data:{"username": u, "password": p},
                success: function (arg) {
                    console.log(arg)
                }
            })
        }
    </script>
    </body>
</html>

因为是在django中,所以网页的注释使用的{# #}
要调用jQuery,所以要在开头声明静态文件{% load staticfiles %}
在jQuery中直接使用$.ajax({})的形式调用Ajax,其中,
url对应的/test2是说你要将数据提交到/test2地址下。
type是说你要用什么方式提交。(使用POST方式时,要注意scrf跨站请求)
data中是你要传送的数据,采用字典键值对的形式传输
success是指回调函数,而其中的参数arg是后台传给前台的数据。

而后台直接这样写就可以接收数据了

def test2(req):
    user = req.GET.get('username')
    pwd = req.GET.get('password')
    return HttpResponse("I got it. hahahaha")

相关文章

网友评论

      本文标题:jQuery使用Ajax

      本文链接:https://www.haomeiwen.com/subject/mytuqqtx.html