简体   繁体   中英

Using JavaScript Onclick Event to pass Data to views.py in Django?

I Have a bit of idea about this to use ajax with the JavaScript to send data to views.py but I am not able to do that.

So what I am trying to do is I have put onclick event on the image so by clicking on that image I should be able to send some value to views.py.

This is Hello.html file:

<img src="" onclick="change()">

JavaScript function:

function change(){
     // Do something here to send data to views.py
 }

Now in views.py

def SomeFunction():
    //To get data here
    

You can use ajax function :

Template:

<img src="" onclick="change(foo, bar)">

javaScript :

function change(foo, bar){
$.ajax({
    url: 'ajax/foo/',
    data : {
        'foo': foo,
        'bar': bar
    },
    success: function (data) {
        $("#idImg").html(data);
    }
});

}

views.py :

def SomeFunction(request):
foo = request.GET.get('foo')
foo = request.GET.get('bar')
...

urls.py

path('ajax/foo/', views.SomeFunction, name='ajax_foobar'),

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