使用JavaScript:函数的语法与jQuery选择进行Ajax调用语法、函数、JavaScript、jQuery

2023-09-10 20:06:14 作者:Autumn □ 暮秋ゝ

我做前端开发的时候只喜欢10%,很好奇这是更好的方式来处理使Ajax调用。这些调用刚刚发布的数据到一个web应用程序,它指定一个动作的名称和ID。

I do front-end dev only like 10% of the time and am curious which is the better way to handle making ajax calls. These calls are just posting data to a web app that specifies an action name and an id.

<a href='javascript:addToList({'action':'set-default-time-zone','id':23})'>set default timezone</a>
<div class='add-to-list action-set-default-time-zone id-23'>set default timezone</div>

我都用了这些年来,但我不知道哪一个是preferred。这似乎是他们得到的相同点到底。你会认为这些是最好的两个备选方案,是其中一个比另一个更好吗?

I have used both over the years but am not sure which one is preferred. It seems like they get to the same point in the end. Would you consider these to be the two best alternatives and is one better than the other?

我已经实现了分区的方法如下:

I've implemented the div method as follows:

$(document).ready(function(){
    $('.add-to-list').click(function(){
        var id=getId($(this).attr("class"));
        var action=getAction($(this).attr("class"));
        $.post('/api/' + action,function(data){
          ...
        },'json')
    });
});


function getAction(str){
    var parts=str.split(' ');
    var phrase='action-';
    for(i=0; i<parts.length; i++){
        var val=parts[i].match(phrase);
        if(val!=null){
            var action=parts[i].split('action-');
            return action[1];
        }
    }
}

function getId(piece){
    var parts=piece.split('id-');
    var frag_id=parts[parts.length-1];
    var part_id=frag_id.split('-');
    var id=part_id[part_id.length-1];
    return id;
}

链接的方法似乎简单明了。

The link method would seem straightforward.

THX

推荐答案

那么第二个方法是,你会叫什么的非侵入式JavaScript 。它被认为是一种更可靠的方法(我会避免长期的好的位置。)

Well the second approach is what you would call Unobtrusive JavaScript. It is believed to be a more robust approach (I'll avoid the term better here.)

不过,你的实现是有点过于复杂。它可以被调低到:

However, your implementation is a bit over-complicated. It could be tuned down to:

HTML:

<div class="add-to-list" data-action="set-default-time-zone" data-id="23">
    set default timezone
</div>

JavaScript的:

JavaScript:

$(document).ready(function () {
    $('.add-to-list').click(function () {
        var id = $(this).attr("data-id");
        var action = $(this).attr("data-action");

        $.post('/api/' + action, function(data) {
          // ...
        }, 'json')
    });
});

的 HTML5规范允许开始数据 - 来携带用户定义的数据。而且它也具有向后兼容性(将与旧的浏览器。)

The HTML5 specification allows for attributes starting with data- to be carrying user-defined data. And it's also backward compatible (will work with older browsers.)