简体   繁体   中英

How do you submit the selected value in a dropdown via ajax in Django

Am a little bit newbie to django ajax so my question might be an easy thing for experts. I have a select option dropdown where i want when the user selects a value from dropdown, the value is submitted via ajax so that i can run querysets in the django backend using the selected value. I can somehow figure out to do this in the backend but need a little help with how to submit this value in the front end by ajax. here is the dropdown code,just basic html,

<select>
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>

I want an ajax function that will send the selected value to server so that i can use it to run a queryset in the django backend and return the result to ajax success function appropriately. Thanks in adavnce

Check that:

<select id="select_form">
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option> 
</select>

var name = $('#select_form').find(":selected").text();
var url = 'your_url_here'+userName+'/';
   $.get(url, function(data)
   {
      //do something with data
   })

I tried like this for the following select dropdown:

<select id="select_dropdown">
<option value='joshua'>joshua</option>
<option value='peter'>peter</option>
....
....
</select>

<script>

$(document).ready(function(){

 $('#select_dropdown').change(function(){
    var e = document.getElementById("select_dropdown");
    var value = e.options[e.selectedIndex].value;

    $.ajax({
        url: "your-url",
        type: "post",
        data: value,
        success: function(data) {

           console.log(data);
        }});

});

</script>

Here's an example using JQuery that places an event handler on the select widget that will call your Django view when the user makes a selection. In this example the selected name is being appended to the URL so that Django can grab it with the following regex in urls.py:

url(r'^path_to_app/(?P<name>\w+)$', 'app.views.function'),

Here's an example:

<select id="chooseme">
<option>--select a name--</option>
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {

    $('#chooseme').change(function(){
        var name = document.getElementById("chooseme").value;
        $.get('/path_to_app/' + name, function(data){
               // do something here with a return value data, if desired
        });
    });
});
</script>

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