简体   繁体   中英

Django Ajax request issues with data returned in my template

In my django project i make an ajax call for dynamically display and populate fields. First of all, in my template i create the element:

Template html

<select class="form-control" onChange="AddOptions(this);">
    {% for entry in all_test %}
        <option id="mainID" value="{{ entry.id }}">{{ entry.descr }}</option>
    {% endfor %}
</select>
<div id = "div_val" class="input-group" style="display: none;">
                <div class="input-group-btn">
                  <button id = "btn_val" type="button" class="btn btn-danger">Test</button>
                </div><!-- /btn-group -->
                <input type="text" class="form-control">
              </div>

then in my js:

start.js

function AddOptions(VarID) {
$.ajax({
    type: "POST",
    url: "ajax",
    data: {mainID: VarID.value},
    success: function (data) {
        $.each(data, function (index) {
            $("#div_val").show();
            console.log("Key: " + data[index].OptionKey+" Val: "+ data[index].OptionVal)
        });
    }
});
}

urls.py

url(r'^ajax$', mainoptions),

and finally my python function called from urls.py:

from frontend.models import temp_main, temp_case, temp_variables


def mainoptions(request):
    if request.is_ajax():
        mainOptions = temp_variables.objects.filter(main_id=int(request.POST['mainID']))
        response = []
        for i in mainOptions:
            vallabel = {}
            vallabel['OptionID'] = i.id
            vallabel['OptionKey'] = i.v_key
            vallabel['OptionVal'] = i.v_val
            response.append(vallabel)
        json = simplejson.dumps(response)
        return HttpResponse(
        json, content_type='application/json'
        )
    else:
       pass

All done, my hidden div "div_val" in template was show, but now i can't understand how can i use the returned data in my template, for, for example, populate the value of the element inside the div (without using jquery inside my js func for do it). How can i close the chain Template -> js -> urls -> view method -> Template ?

Many Thanks in advance

When you use server side rendering, you cannot close the "chain" you are refering to as easily. This is because what Django does in this case is serve all the HTML and JS (at leas the JS inside your HTML view) in a single initial response. The ajax requests you do after that will not be bound to the variables you send initially in your response because this variables are populated when the render() function is called. After that moment, you cannot add or update the variables that were sent to the HTML template.

The only way you can manage rendering small parts of HTML is using JQuery or making your backend a REST API with Django Rest Framework and moving to a more complete frontend framework like Angular or React. The are many discussions over server side rendering vs client side rendering.

You can read more about it here:

https://medium.com/@adamzerner/client-side-rendering-vs-server-side-rendering-a32d2cf3bfcc

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