简体   繁体   English

什么是使用AJAX修改DOM的最干净方法

[英]What is the cleanest way to modify DOM using AJAX

I've search other the internet how to modify my HTML page after an ajax request. 在ajax请求之后,我已经在互联网上搜索了如何修改HTML页面。 I've found many different solutions and I don't know which one to use. 我找到了许多不同的解决方案,但我不知道该使用哪种解决方案。 Here are the options I consider: (by the way, I'm not using jQuery and I'm starting in AJAX) 这是我考虑的选项:(顺便说一句,我没有使用jQuery,而是从AJAX开始)

  1. The server build all the the DOM in PHP with some "echo" and we just use innerHTML = xhr.responseText on client side. 服务器使用一些“ echo”来构建PHP中的所有DOM,而我们只在客户端使用innerHTML = xhr.responseText

  2. The server build an XML document and JavaScript use the XML file to change the DOM. 服务器构建一个XML文档,而JavaScript使用XML文件更改DOM。 For this second solution, I'm not sure how to do it. 对于第二种解决方案,我不确定该怎么做。

Do you know which solution to use? 您知道使用哪种解决方案吗? And do I forget some other solutions? 我会忘记其他解决方案吗?

Using echo as innerHTML is begging to have people inject all kinds of fun stuff into your code. 使用echo作为innerHTML恳求人们将各种有趣的东西注入您的代码中。

At this point in the game, you should probably be using JSON to send messages back and forth, and writing JS which will create what you want to see in the browser. 在游戏的这一点上,您可能应该使用JSON来回发送消息,并编写JS,以创建您想在浏览器中看到的内容。

If I were creating a messaging system, I might go like this: 如果要创建消息传递系统,则可能会这样:

In-Browser (unstyled) 浏览器 (无样式)

• Norguard  
  My message
  2012-10-02 10pm

• Norguard
  Message 2
  2012-10-02 11pm

HTML 的HTML

<!-- basic idea of what I'm working with in the end result -->
<ul id="message-list">
    <li><span class="username">Norguard</span><p class="content">My Message</p><time datetime="2012-10-02T22:00:00.000Z" pubdate>2012-10-02 10pm</time>
</ul>

JS (program) JS (程序)

// This might be a really basic implementation of functions to display messages
var Messager = {
    parent : document.getElementById("message-list"),
    update : function () { /* get messages from server */ },
    buildMessage : function (message) {
        var frag = document.createDocumentFragment,
            name = document.createElement("span"),
            body = document.createElement("p"),
            time = document.createElement("time");

        name.className = "username";
        body.className = "content";
        time.setAttribute("pubdate", "pubdate");

        name.innerText = message.userName;
        body.innerText = message.content;
        time.setAttribute("datetime", message.timestamp);
        time.innerText = message.friendlyDate;

        frag.appendChild(name);
        frag.appendChild(body);
        frag.appendChild(time);

        return frag;
    },

    buildMessages = function (messages) {
        var parentFrag = document.createDocumentFragment(),
            messenger = this;

        messages.forEach(function (message) {
            var li = document.createElement("li"),
                messageFrag = messenger.buildMessage(message);
            li.appendChild(messageFrag);
            parentFrag.appendChild(li);
        });

        return parentFrag;
    },

    writeMessages = function (newMessages) {
        this.domElement.appendChild(newMessages);
        // or do whatever sorting is required, et cetera
    }
};

JS (result-handling) JS (结果处理)

// this might be like what your XHR callback looks like (this is really basic)
xhr.onreadystatechange = function () {
    if (!this.readyState === 4 && (!this.status == 200 || !this.status == 302)) { return; }

    var json = "",
        data = "",
        messages;

    json = this.responseText;
    data = JSON.parse(json);
    messages = Messager.buildMessages(data);
    Messager.writeMessages(messages);
};

JSON (response-text) JSON (响应文本)

// What your JSON response would be
[
    {
        "username"  : "Norguard",
        "content"   : "My message",
        "timestamp" : "2012-10-02T22:00:00.000Z",
        "friendlyDate" : "2012-10-02 10pm"
    }, {
        "username"  : "Norguard",
        "content"   : "Message 2",
        "timestamp" : "2012-10-02T23:00:00.000Z",
        "friendlyDate" : "2012-10-02 11pm"
    }
]

Note that you shouldn't do things like put friendly dates in your JSON, and instead, you should convert into the user's local time, using JS and the timestamp in each message... ...but this is a demonstration of how to get through the whole package with as few frills as possible. 请注意,您不应该执行诸如在JSON中放入友好日期之类的操作,而是应该在每个消息中使用JS和时间戳将其转换为用户的本地时间... ...但这只是如何演示的示例尽量减少多余的装饰。

From PHP, you would get your messages in whatever way they were stored (database, csv, different text files... ...streamed from Twitter... ...whatever), and you'd put them all in an array. 从PHP中,您将以任何存储方式(数据库,csv,不同的文本文件...从Twitter流式传输...等等)获取消息,并将它们全部放入一个数组中。

PHP 的PHP

// Your PHP for the data above might look like this:
$msgArray = array(

    array( "username" => "Norguard",
           "content"  => "My message",
           "timestamp" => "2012-10-02T22:00:00.000Z",
           "friendlyDate" => "2012-10-02 10pm"        ),

    array( "username" => "Norguard",
           "content"  => "Message 2",
           "timestamp" => "2012-10-02T22:00:00.000Z",
           "friendlyDate" => "2012-10-02 11pm"        )
);

$jsonData = json_encode($msgArray);

echo $jsonData;

There may well be errors in this -- I didn't write this in a code-pad, I just did it here, off the top of my head. 这很可能有错误-我没有在密码键盘中编写此代码,只是在这里写了我的想法。

It's also not meant to be 100% complete code. 这也不意味着是100%完整的代码。 I didn't cover setting up the XMLHttpRequest, for instance, or doing any event-handling, or doing any UI stuff (like sorting the messages by timestamp, or removing duplicates or adding an update button). 例如,我没有介绍设置XMLHttpRequest或进行任何事件处理或进行UI的任何工作(例如按时间戳对消息进行排序,删除重复项或添加更新按钮)。

This is sort of just the bare-necessities of getting JSON data from PHP into JS (Chrome/FF/Safari/newer IE), and a very simple strategy for putting that data in HTML, and putting it into the page. 这只是将PHP中的JSON数据导入JS(Chrome / FF / Safari /较新的IE)的基本必需品,并且是一种非常简单的策略,可以将数据以HTML格式放入页面中。

The "cleanest way" imo is to use cross browser solution that returns an object to your response logic. imo的“最干净的方式”是使用跨浏览器解决方案,该解决方案将对象返回到您的响应逻辑。 You can use echo but that would be the "dirty way" imo haha. 您可以使用echo,但这将是imo haha​​的“肮脏方式”。

I would suggest looking at returning json objects via ajax calls. 我建议查看通过ajax调用返回json对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 什么是获得JQuery ajax请求进度的最干净的方法? - What is the cleanest way to get the progress of JQuery ajax request? 用Node.js的FileSystem(fs)模块将多个DOM元素保存和加载为JSON的最干净方法是什么? - What is the cleanest way to save and load multiple DOM elements as JSON with the FileSystem(fs) Module from Node.js? 设计表单处理以支持支持AJAX的浏览器和非AJAX浏览器的最简洁方法是什么? - What is the cleanest way to design form processing to support AJAX-capable browsers and non-AJAX browsers? 没有 .animate() jQuery 的最简洁的动画方式是什么? - What is the cleanest way to animate without .animate() jQuery? 关闭JavaScript中承诺的连接的最干净的方法是什么 - What is the cleanest way to close promised connection in javascript 在AngularJS中,最简单的声明工厂/服务的方法是什么? - In AngularJS what is the cleanest way to declare a factory / service? 修改DOM元素和限制重排的最有效方法是什么? - What is the most efficient way to modify DOM elements and limit reflow? 在laravel中使用来自ajax的过滤数据将VUE组件“附加”到DOM的正确方法是什么? - What is the proper way to "append" VUE component to DOM using my filtered data from ajax, in laravel? 在不使用双 for 循环的情况下将对象转换为列表的最简洁方法是什么? - What's the cleanest way to turn an object into a list without using a double for loop? 反应:不使用“ this”访问组件的最干净方法 - React: Cleanest way of accessing component without using “this”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM