Recommendations for returning and displaying data from AJAX calls

I have a specific jquery / php interaction configured on the page. It sends some data to the server and returns data records, which should then be aligned on the page for comparison and possible actions beyond this.

My question is, what is the best practice for returning information and then displaying it?

  • Return a JSON object and then create html on the fly with js and display data?
  • Returns a JSON object, and then put that data into already created containers for the data on the page?
  • Returns pure html from the server and just put this on the page?

I rolled them over my head last night and couldn't figure out if one way would be better for any particular reason.

I am not a guru-guru, so I was not sure about the pros / cons and reservations to these various methods.

+5
source share
7 answers

I think it ends depending on your application.

Pure HTML is the easiest, you just go into place and viola. JQuery makes it easy to add the right events and what not.

However, whenever I used AJAX, it always turned into returning JSON and creating elements on the fly. If you, for example, populate a tree, it can become dirty to get proper nesting. This forces you to do client-side code anyway when just using JSON from the very beginning becomes cleaner.

, , JSON - , HTML .

+7

, . , , JSON ( ), " ", onSuccess , , , , ( , ..).

+4

" " . , , JSON - , JavaScript-, , HTML DOM. , - , , JavaScript; HTML .

+2

, , . , ...: -)

jQuery, :

$(function() {
    $.getJSON('/some/page',{foo:bar,bar:foo},function(json) {
        if(json.outcome == 'success') {
            $('body').prepend(json.html);
        } else {
            // Somehow let the user know why it didn't work
            alert(json.error);
        }
    });
});

(PHP ), :

<?php // Page: '/some/page'

/* Blah Blah Blah... do whatever needs to be done... */

// If everything turns out okay (assuming '$output' is the HTML 
// you want to display...
echo json_encode(array('outcome'=>'success','html'=>$output));

// If something goes wrong... just do:
echo json_encode(array('outcome'=>'error','error'=>'Uh oh... something is broken'));

, , - - . . , , json. HTML, - , , " " - , ... ... .

, , , , ( ) HTML DOM , JSON , , , . , , - , . HTML JSON.

jQuerying: -)

+1

: AJAX: (JSON, XML) HTML?.

HTML, HTML DOM. , , JSON .

Person, , Person.Name Person.Preferences, . , , HTML Javascript, RIA.

0

, HTML .

, HTML javascript , javascript.

- json javascript. , , , javascript.

, Flickr . o . , .

0

HTML - . gzip , javascript , . , javascript HTML - , , MVC.

-1

All Articles