Skip to content Skip to sidebar Skip to footer

Replace Divs With Content From Json Call

I am receiving content from a JSON call and I would like to populate 3 object that returned with response in news_item class as follows:

Solution 1:

Mind you jQuery templating is still in beta (can be DL here: https://github.com/jquery/jquery-tmpl)

Create a jQuery template of this HTML, with the Title/ID/Content etc where they will be appearing ${TITLE}/etc. Basically like this:

<divclass="news_item"style="margin-left: 0 !important;"><divclass="ni_image"><ahref="/HaberDetay/${TITLE}/${ID}"><imgsrc="IMAGE"width="203"height="109"/></a></div><divclass="ni_text"><divclass="ni_text_title">${TITLE}</div><divclass="ni_text_content"> 
            ${CONTENT}
        </div></div></div>

Then just create the template and append it to news.

$('#yourTemplateScriptArea').tmpl(newsByCity).appendTo('.news');

Here's an intro on Templating if you've never done it before. http://stephenwalther.com/archive/2010/11/30/an-introduction-to-jquery-templates.aspx

Solution 2:

To create new elements you can create them with JS or jQuery. jQuery is easier but has a higher overhead.

// Element to append tovar target = $('.news');

// Create the new element in a jQuery object// and use the appendTo method to attach it// to the DOM element
$('<div />').html('<p>New div created</p>')
            .appendTo(target);

Alternatively you can find existing dom elements and replace the text or HTML

var target = $('.news');

// Replacing text
target.find('.ni_text_title').text('New news title');

// Replacing HTML
target.find('.ni_text').html('<div class="ni_news_text">...</div>');

You can empty the textual or HTML contents of an element by passing an empty string to the .html and .text methods. If you leave them blank the method will return the current text or HTML of that element.

Hope that helps.

Post a Comment for "Replace Divs With Content From Json Call"