简体   繁体   中英

Javascript works only once when function calls via button

I have a page with Javascript that calls a Django URL, but this call just work once.

The html code is here:

<script>
        function myFunction(pk) {
            if ($.data(this, 'submitted')){
                return false;
            }
            $.data(this, 'submitted', true);

            $.get("{%url 'myViewURL' %}",{req:pk}, function (data) {
                $.data(this, 'submitted', false);//libero

            });
        }</script>

Button code

<button onclick="myFunction({{id}});">Click Me</button>

The view code:

def myFuncView(request):
p_id=request.GET['req']
do_stuff(p_id)
return  redirect('anotherURL',p_id,permanent=True)

When is the first time I press the button, it fires, but after that it does not work anymore, even if I refresh the page or go to another page and come back!

this inside the get function refers to the ajax request, not the button which initiated it.

You need to store a reference to this , so you can then use it in a different context:

var self = this;
$.get("{%url 'myViewURL' %}", {
    req: pk
}, function (data) {
    $.data(self, 'submitted', false); //libero

});

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