简体   繁体   中英

How to process a JSON response and output html from it?

Up until now I have used the django template system to perform this kind of action. Simply respond to the ajax request with an html template.

Right now I am trying to implement an autocomplete search feature and I want to send back to the client the response in json format.

All good and set up to this point. This is my jQuery part:

$(document).ready(function(){
    $("#id_q").keyup(function(){ //the form text input
        autocomplete(this.value);
    });

    function autocomplete(inputString) {
        if(inputString.length == 0) {
            $('#autocomplete').fadeOut();
        }
        else {
            $.get("/autocomplete/", {q: ""+inputString+""}, function(data) {
                $('#autocomplete').fadeIn();
                $('#autocomplete').html(data);
            });
        }
    }
});

When using a django template as a response, the #autocomplete div was showing up nice and as expected with .html(data), thats because I was setting up the html in the template beforehand, as I wanted it to be shown.

How do I process the data sent from the server (in json format)? Data looks something like this:

[{'title':'titleString', 'descr':'desriptionString', 'url':'itemAbsoluteUrl'}, ..]

In order to obtain my #autocomplete html, say, something like:

<li><a href="data.url">data.title<br>data.descr</li>

Thanks for any feedback!

First of all, in order to format the return data as a JSON object, you need to specify in the get call that the return type is json. After that, you reference data based on the json key value pairs, eg data.results. (Note that results must be a key in your JSON object).

$.get("/autocomplete/", {q: ""+inputString+""}, function(data) {
            $('#autocomplete').fadeIn();
            $('#autocomplete').html(data.results);
}, "json");

I'm not sure what your current format is, but just to clarify, you probably don't want to send raw HTML through JSON. Instead, keep the HTML on your client page, and have get return some data to populate it.

Try

var li = $('<li><a href="'+data.url+'">'+data.title+'<br/>'+data.descr+'</a></li>')

and then you can insert li where you want, or

$('#autocomplete').html('<li><a href="'+data.url+'">'+data.title+'<br/>'+data.descr+'</a></li>');

To iterate through the results

$.each(results, function(index, value){
...
})

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