我有一个小型应用程序,它通过 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/