jQuery的阿贾克斯 - 返回JSON或纯HTML更好 [英] jquery ajax - return json or plain html better

查看:72
本文介绍了jQuery的阿贾克斯 - 返回JSON或纯HTML更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在从阿贾克斯的时候回归, 我应该返回的JSON恩code,并使用jquery.parseJSON 并使用document.createElement方法和附加数据刚刚创建的元素中。

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.

或最好是返回的HTML文本?

or it is better to return as html text?

例如,

<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 ......对不起,我的语法错误

Ammended... sorry for my bad grammar

<打击>当然,这只是一个例子,真正的情况下,将有大量的数据,可能会在HTML表格格式。

当然,这只是一个例子,真正的情况下,将有大量的数据。

Of course, this is just a example, real case it would have a lot of data.

如果有大量的数据,那么我就需要写很多document.createElement方法的()。 它消耗的时间来写这样的 使用document.createElement('表'); 使用document.createElement('TR');

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');

而不是(返回为HTML,只是附加在容器中)

instead of (Return as HTML and just append in the container)

对于我来说,我认为第二格式(返程HTML)更容易。

For me I think second format( return HTML ) is easier.

但不知道对性能明智的,哪个好?

But not sure for the performance wise, which is better?

请指教。

推荐答案

无论塞巴斯蒂安和Zain公司拥有有效的点。这取决于什么样的样的表现的你在说什么。

Both Sébastien and Zain have valid points. It depends what kind of performance you're talking about.

如果你想降低您的服务器的带宽,那么你应该返回JSON,并使用客户端JavaScript创建您的显示。

If you want to reduce your server's bandwidth, then you should return JSON and create your display using client-side javascript.

然而,如果你的数据集较大,在大多数机器上创建显示的客户端可能会落后于浏览器,使用户界面变得反应迟钝。如果这对你很重要,那么你可以考虑从服务器返回的HTML。

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.

这篇关于jQuery的阿贾克斯 - 返回JSON或纯HTML更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆