Reputation: 653
When the time return from ajax, I should return as json encode, and use jquery.parseJSON and use document.createElement and append the data inside the Element that just created.
or it is better to return as html text?
example,
<div id="contentcontainer"></div>
$.ajax({
type: "POST",
url: "some.php",
data: "name=John",
success: function(msg){
msgObj = jquery.parseJSON(msg);
var div = document.createElement('div');
div.style.color="red";
$(div).append(msgObj.name);
$('#contentcontainer').append(div);
}
});
//some.php
if($_POST['name']){
echo json_encode( array('name'=>$_POST['name']) );
}
OR I should do like this?
<div id="contentcontainer"></div>
$.ajax({
type: "POST",
url: "some.php",
data: "name=John",
success: function(msg){
$('#contentcontainer').append(msg);
}
});
//some.php
if($_POST['name']){
echo '<div style="color:red">'.$_POST['name'].'</div>';
}
Ammended... sorry for my bad grammar
Of course, this is just a example, real case it would have a lot of data, may be in html table format.
Of course, this is just a example, real case it would have a lot of data.
if it has a lot of data, then I need to write a lot of document.createElement(). and it consumes time to write like this document.createElement('table'); document.createElement('tr');
instead of (Return as HTML and just append in the container)
For me I think second format( return HTML ) is easier.
But not sure for the performance wise, which is better?
Please advise.
Upvotes: 8
Views: 9859
Reputation: 8765
Both Sébastien and Zain have valid points. It depends what kind of performance you're talking about.
If you want to reduce your server's bandwidth, then you should return JSON and create your display using client-side javascript.
However if your dataset is large, on most machines creating your display client-side could lag the browser and cause the UI to become unresponsive. If that is important to you then you might consider returning HTML from the server.
Upvotes: 6
Reputation: 6043
no, I would not recommend returning html
from php page. only return the json
data and parse it on client side and show on UI. because html
will always be heavier than json. so if you use json it will save your bandwidth
.
In case you want an example, just go and check out what twitter
is doing, they only return json and then manipulate json on client side.
Upvotes: 0
Reputation: 1106
Yes you should return HTML if you don't have manipulation/interpretation to do with the result of your AJAX call.
Upvotes: 0