社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

Django模板。API请求导致页面导航到查询url

Alex • 5 年前 • 1662 次点击  

我有一个django模板,其中包含一个按钮:

<button type="submit" class="btn btn-primary" onclick="getRota()">Make Rota</button>

getRota()函数在脚本中定义如下:

<script>
    function getRota() {
        var startDate = $("input[name='rota_start']").val();
        var endDate = $("input[name='rota_end']").val();
        fetch(`{{ rota_url }}start=${startDate}&end=${endDate}`, {
            method: "GET",
            headers: {
                "X-CSRFToken": getCookie("csrftoken"),
                Accept: "application/json",
                "Content-Type": "application/json"
            }
        })
        .then(response => response.json())
            .then(data => {
                    $("#rota_form").append(`<a href=${data.url} target="_blank">Text Rota</a>`);
                });
    }

</script>

奇怪的是,按下按钮会导致页面发出API请求,附加链接(目前为止一切都很好),然后不久,导航到原始页面(而不是API)的URL,使用 start=${startDate}&end=${endDate} (从api url)附加到它。。。

我真的不知道从哪里开始。。。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49886
 
1662 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Robin Zigmond
Reply   •   1 楼
Robin Zigmond    6 年前

按钮有 type="submit" 你不打电话 preventDefault ,所以它所属的表单正在提交。这可能解释了您看到的情况,尽管您没有共享表单html-我猜它是通过GET和has提交的 start end 领域。

因为看起来不需要表单直接提交到服务器(就像通过ajax一样),所以至少有3个非常简单的修复:

  • type="button" 而不是 type=“提交” ( submit 是默认值,因此不能忽略它)
  • 完全删除表单,只需输入和一个按钮
  • 呼叫 防止违约 在Javascript中的事件