javascript - jQuery .each() 方法或 .html() 方法

标签 javascript jquery html

我有一个小型应用程序,它通过 PHP 后端从数据库加载 HTML 内容。目前 jQuery 将 html 数据从 PHP 文件加载到主页上的 DIV,每 5 秒左右发生一次 setInterval() $('#div').html(html);。所有格式都在 CSS 中完成,数据结构从 php 文件中呼应出来。我还使用 jQuery 通过 PHP 将数据发布到数据库,因为这是一个小型聊天应用程序。我的问题是提取这些数据的更快或更有效的方法是什么,要么使用 json 并通过 jQuery .each() 方法将每个元素解析到其结构中,要么继续使用我当前的 .html() 方法来加载数据并通过 PHP 回显完整的数据结构?感谢您的宝贵时间。

最佳答案

我个人将结构回显到 PHP 中的 JSON 对象。然后在 javascript 中解析它并通过 .html() 将其放入容器中。

我认为这比替代方案要好得多,因为您在 php 中有干净整洁的可编辑代码,只需使用 javascript 将其放在需要的地方。

在我的 php 中:

    $response['error'] = false; // if you get an error set this to true
    $response['html'] = ''; // set this wherever you like.
    alternately if you needed to break it up
    $response['html_A'] = '';
    $response['html_B'] = '';


>     in the end


    echo json_encode($response);

在 JavaScript 中

$.post(function(r){
  response = JSON.parse(r);
   if (response.error !== true){
     $('#someDiv').html(response.html);
   }
   else {
     alert (response.errorMessage);
   }
}

做一个 $.each 循环似乎很费力。特别是当您决定添加/修改 php 生成的一些输出时。

关于javascript - jQuery .each() 方法或 .html() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15504466/

相关文章:

javascript - Highchart 不显示 unicode 字符

jquery - HTML5 中的 3D 图像转换

单页模板中的 JQuery Mobile Ajax 导航

php - 如何使顶部导航中的单个链接在 wordpress 中具有不同的背景颜色?

JavaScript:在一天开始时更新一次本地存储

php - HTML5音频元素

javascript - 非宽度特殊字符去除

html - CSS - 悬停时文本 move

javascript - 如何一成不变地改变状态 React

javascript - 在 PhoneGap 中调用 window.location.href 触发网络浏览器