【问题标题】:Unable to call javascript function django rest API无法调用javascript函数django rest API
【发布时间】:2019-03-21 19:09:49
【问题描述】:

您好,我是 html 和 javascript 的初学者。我使用 python django 应用程序编写了一些 REST API。我正在尝试从 html 和 Javascript 调用登录 API。但无法调用函数和我的 API URL。

这里是代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'>

   $('#send').click(function(e)
    {
    e.preventDefault();

    data = {

        "username": $('#username').val(),

        "password": $('#password').val()

     };

    $.ajax({

        type: "POST",

        url: "http://127.0.0.1:8000/user/login/",

        data: JSON.stringify(data),

        dataType: "json",

        contentType: "application/json",

        success: function(data) {console.log(data)},

        error: function (rs, e) {console.debug(rs)}

    });

});

            <div class="grad"></div>

            <div class="header">

                    <div>Site<span>Random</span></div>

            </div>

            <br>

            <div class="login">

                            <input type="text" id="username" placeholder="username" name="user"><br>

                            <input type="password" id="password" placeholder="password" name="password"><br>

                            <input type="submit" id="send" class="btn" href="#">Send</a>

            </div>

我正在以下列方式运行我的 django 应用程序 Python manager.py 运行服务器:8000 端口。我可以通过邮递员得到回复。但从 index.html 调用时无法得到响应

感谢您的帮助

【问题讨论】:

  • 正在使用document.ready$(function(){})。等待 DOM 加载。
  • 我如何在这里使用它。
  • 在您的点击处理程序中执行 console.log() 并查看日志是否显示。如果它没有显示,则表示 jquery 没有找到元素,因为页面还没有准备好。
  • 您遇到了什么错误?
  • 我遇到了错误

标签: javascript python html api django-rest-framework


【解决方案1】:

您的所有代码都应该在document.ready 中。不确定您是否正在使用它,但我在您的代码中没有看到它。我看到你选择元素没问题。

$( 文档 ).ready(function() { console.log("准备好了!"); });

在文档“准备就绪”之前,无法安全地操作页面。 jQuery 会为您检测到这种准备状态。 $( document ).ready() 中包含的代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 2018-11-10
    • 2021-09-03
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多