简体   繁体   English

使用JavaScript将URL发送到服务器

[英]Sending a URL to server with JavaScript

I am not a great programmer and would like help. 我不是一个优秀的程序员,并且需要帮助。

The javascript code below is supposed to send the url in the format /update/1/3 to my django test server to update an item. 以下javascript代码应该将格式为/ update / 1/3的url发送到我的django测试服务器以更新项目。 However when I try, I only see a post of /update/ in the console log. 但是,当我尝试时,我只会在控制台日志中看到/ update /的帖子。

<script type="text/javascript">
    function goTo()
    {
        var url = '/update';
        var quantity = document.forms[0].quantity.value;
        var menuitem_id = document.forms[0].menuitem_id.value;
        window.location = url+'/'+menuitem_id+'/'+quantity;
        return false;
    }
</script>

What am I doing wrong? 我究竟做错了什么?

As requested, please see the HTML: 根据要求,请参见HTML:

<div class="container">
<td class="table">
    <form method="post" action="." onsubmit="return goTo()">
    <div>
    {% csrf_token %}
        {% if item %}
        <label for="quantity">How much {{ item.product.name }} from {{ item.product.restaurant.name }} do you want?</label>
        <input style="height:25px;font-size:12pt;" type="text" name="quantity" value="{{ item.quantity }}" id="quantity" size="2" class="quantity" maxlength="5"/>
        <input type="hidden" name="menuitem_id" value="{{ item.product.id }}" id="menuitem_id"/>
        </td>
        <td>
        {% endif %}
    </div>
    <button class="btn btn-primary" type="submit">Update</button>
    </form>
</td>
</div>

The code you posted looks fine. 您发布的代码看起来不错。 Make sure "quantity" and "menuitem_id" are the names (not the ids) of the inputs in the first form on the page (forms[0]). 确保“ quantity”和“ menuitem_id”是页面上第一个表单(forms [0])中输入的名称(而不是id)。 Many times, for example, people forget that the search bar at the top of their page is technically the first form. 例如,很多时候,人们忘记了页面顶部的搜索栏在技术上是第一种形式。

Also, if these inputs are user-specified and you're anticipating them to always be numbers, it may also help to clean out any unwanted characters with something like: 另外,如果这些输入是用户指定的,并且您希望它们始终是数字,则也可以使用以下方法来清除所有不需要的字符:

var quantity = document.forms[0].quantity.value.replace(/[^0-9]/g,'');

..which will remove any non-numeric characters from the input. ..将从输入中删除所有非数字字符。 This will prevent whitespace from mucking up the URL path and also help (a little bit) to protect your users from javascript injection attacks. 这将防止空格破坏URL路径,并且(一点点)有助于保护您的用户免受javascript注入攻击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM