我应该如何使用HTML客户端UI元素的服务器端数据相关联? [英] How should I associate server-side data with client-side UI elements in HTML?

查看:147
本文介绍了我应该如何使用HTML客户端UI元素的服务器端数据相关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这个问题不断地在开发AJAX应用程序。比方说,我希望用户能够点击与我的网站上,这会导致一个AJAX请求每个评论关联的标志的图标被发送到服务器,请求注释进行标记。我要评论ID与客户端上的注释联系起来,使得AJAX请求可以传送到发表评论我要标记的服务器。

此页解释了许多方法来以这种方式进行注释的HTML,但没有它们是非常令人满意的。虽然我可以只使用一个ID或类属性的注释ID与标志按钮(比如:id =comment_1998221)相关联,这将失败,更复杂的数据并不很好地成为这些属性(例如任意的字符串)。是否有这样的事情最好的做法?每次我需要这样做,我结束了与一些杂牌组装电脑一样使用id属性,隐藏表单域,或更糟糕的跨度设置为显示:无

在HTML5数据 - *属性似乎是一个完美的解决方案,但我已经看到了很多仇恨走向他们,这让我觉得人一定已经有他们满意的解决方案。我很想知道它是什么。

解决方案
  

本页面介绍了一些方法来以这种方式注释HTML,但他们都不是很理想。

不过,他们是pretty的多少你已经有了。虽然该网页是不是一个非常好的总结,有错误,这错误地理解什么是不显眼的JavaScript的意思。

例如它实际上是完全有效的把体内的脚本元素 - 一个表元素只是没有直接内。可以把所有的脚本片段在表的底部,或者把每一行中它自己的表,或甚至在某些限制条件,如果你正打算变异的DOM中,行内的问题。

设置ID =评论-123然后扫描所有行有一个ID以'comment-'是为您的特定情况下,确实不错。对于设置非识别额外的信息属性,你可以使用任何HTML5数据属性,或使用如劈入类名。 类=评论型富数据吧。当然,这两个ID和类名有他们什么角色可以使用的限制,但它可以连接code的任意字符串到有效的字符串。例如,您可以使用自定义URL式编码隐藏非字母数字字符:

 < TR类=问候语 -  Hello_21_20_E2_98_BA>
    ...
< / TR>

功能getClassAttr(EL​​,名称){
    VAR preFIX =名称+' - ';
    VAR类= el.className.split('');
    对于(VAR I = classes.length;我 - 大于0){
        如果(类[I] .substring(0,prefix.length)== preFIX){
            VAR值=等级[I] .substring(prefix.length);
            返回去codeURIComponent(value.split(_)加入('%'));
        }
    }
    返回null;
}

VAR问候= getClassAttr(TR,'问候'); //你好!☺
 

您甚至可以存储复杂的非字符串值以这种方式,通过编码它们的JavaScript或者JSON字符串,然后使用EXEC检索它们(或JSON.parse如果有的话)。

不过,如果你是把什么不平凡的在那里它很快就会变得混乱。这就是你可能preFER意见。您可以在这里除了序列适合什么' - ',这是很容易逃脱,如果它发生拿出一个字符串

 <表>
    < TR类=评论>
        < TD> ...< / TD>
        <  -  {ID:123,用户:456}  - >
    < / TR>
< /表>

功能getLastComment(节点){
    变种结果= [];
    对于(VAR I = node.childNodes.length;我 - 大于0;)
        如果(node.childNodes [我] == 8)
            返回node.childNodes [I]
    返回null;
}

VAR用户= getLastComment(TR)。用户;
 

摘要警告说,这可能无法保证正常工作,因为XML解析器可以丢弃的意见,但随后DOM Level 3的LS解析器必须让他们在默认情况下,每一个浏览器和主要的XML库迄今一样。

I run into this problem constantly while developing AJAX applications. Let's say I want users to be able to click on a "flag" icon associated with each comment on my site, which results in an AJAX request being sent to the server, requesting that the comment be flagged. I need to associate a comment id with the comment on the client side so that the AJAX request may communicate to the server which comment to flag.

This page explains a number of ways to annotate HTML in this manner, but none of them are very satisfactory. While I could just use an id or class attribute to associate the comment id with the flag button (e.g. id="comment_1998221"), this fails with more complex data that doesn't fit well into those attributes (e.g. arbitrary strings). Is there a best practice for this sort of thing? Every time I need to do this, I end up with some kludge like using the id attribute, a hidden form field, or worse yet a span set to display:none.

The HTML5 data-* attributes seem like a perfect solution, but I've seen a lot of animosity toward them, which makes me think that people must already have a solution they're happy with. I'd love to know what it is.

解决方案

This page explains a number of ways to annotate HTML in this manner, but none of them are very satisfactory.

Still, they are pretty much all you've got. Although that page isn't a terribly good summary, there are errors and it misunderstands what ‘unobtrusive’ JavaScript means.

For example it is in fact perfectly valid to put a script element inside body — just not directly inside a table element. You could put all the script fragments at the bottom of the table, or put each row in its own table, or even, with some limitations if you are intending to mutate the DOM, inside the row in question.

Setting "id="comment-123"" then scanning for all rows with an id starting with ‘comment-’ is indeed good for your particular case. For setting non-identifying extra info attributes, you could use either HTML5 data-attributes or hack it into the classname using eg. "class="comment type-foo data-bar"". Of course both IDs and classnames have their limits about what characters you can use, but it's possible to encode any string down to valid strings. For example, you could use a custom URL-style encoding to hide non-alphanumeric characters:

<tr class="greeting-Hello_21_20_E2_98_BA">
    ...
</tr>

function getClassAttr(el, name) {
    var prefix= name+'-';
    var classes= el.className.split(' ');
    for (var i= classes.length; i-->0;) {
        if (classes[i].substring(0, prefix.length)==prefix) {
            var value= classes[i].substring(prefix.length);
            return decodeURIComponent(value.split('_').join('%'));
        }
    }
    return null;
}

var greeting= getClassAttr(tr, 'greeting'); // "Hello! ☺"

You can even store complex non-string values in this way, by encoding them JavaScript or JSON strings then retrieving them using exec (or JSON.parse where available).

However, if you are putting anything non-trivial in there it soon gets messy. That's where you may prefer comments. You can fit anything in here except the sequence '--', which is easily escaped if it happens to come up in a string.

<table>
    <tr class="comment">
        <td>...</td>
        <!-- {"id": 123, "user": 456} -->
    </tr>
</table>

function getLastComment(node) {
    var results= [];
    for (var i= node.childNodes.length; i-->0;)
        if (node.childNodes[i]==8)
            return node.childNodes[i];
    return null;
}

var user= getLastComment(tr).user;

The summary warns that this may not be guaranteed to work because XML parsers may discard comments, but then DOM Level 3 LS parsers must keep them by default, and every browser and major XML library so far does.

这篇关于我应该如何使用HTML客户端UI元素的服务器端数据相关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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