简体   繁体   中英

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. However when I try, I only see a post of /update/ in the console log.

<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:

<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]). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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