在提交之前获取ajaxLink按钮的id


Get the id of the ajaxLink button before submission

我在Yii框架中创建了一个ajax链接(CHTML::ajaxLink)(而不是ajax表单提交按钮),它通过ajax将一些值传递给控制器。有多个链路将不同的值传递给控制器。我想在将值传递给控制器之前(在jquery.ajax选项的"beforeSend"中)获得单击链接的id/class属性。简单地说,我只想获得生成ajax请求的id/class属性。帮助

更新::这是代码

echo CHtml::ajaxLink ("Click Here",
                              Yii::app()->createUrl('default/del/id/6'), 
                              array(
                                    'beforeSend' => 'function(){
                        //I want to get the id of the link here     
    }',
                                    'complete' => 'function(){
                            }',
                                    'update' => '#loadContent'),
        );
The above code will generate the following a tag:-
<a href="#" id="yt1">Click Here</a>

当用户点击上面的链接时,我想在ajaxLink。

我尝试了以下代码:

 'beforeSend' => 'function(){
 $("a").click(function(){
    var a = $(this).attr("id");
    alert(a); 
 }

上面的代码是有效的,但是只有当链接被点击两次时,id才会被提醒。在第三次点击时,id会被提醒两次,并在随后的点击中不断增加。我对这个奇怪的问题一无所知。

您可以使用$.proxy(),将函数的上下文更改为锚定当前ajax对象的标签:

'beforeSend' => '$.proxy(function(jqXHR,settings){
        console.log($(this).attr("id"));// or alert($(this).attr("id"))
        // rest of your function
        // you can still use the jqXHR object, and the settings map to manipulate the ajax call
},this)'

编辑:

让我告诉你为什么警报数量在随后的点击中不断增加。

之所以会发生这种情况,是因为每次单击时,都会有一个新的单击处理程序与<a>关联,因为这一行:

$("a").click(function(){...})

所以当你第一次点击时,函数调用的顺序是:

beforeSend callback
assign click handler (1)

所以目前还没有警报。

第二次:

1st click handler's alert
beforeSend callback
assign click handler (2)

第三次:

1st click handler's alert
2nd click handler's alert
beforeSend callback
assign click handler (3)

等等,因为它不断增加。

第2版

更好的选择是,您可以使用context选项来创建上下文,即刚才单击的链接:

'context'=>'js:this', // right now 'this' is link, so we can pass it
'beforeSend'=>'function(){// i would suggest using the signature 'function(jqXHR,settings)' so that 
    // you can modify the ajax call if you need to
    console.log($(this).attr("id"));// or alert($(this).attr("id"))
    // rest of your function
}'

来自jquery的ajax文档:

默认情况下,上下文是一个表示调用中使用的ajax设置的对象($.ajaxSettings与传递给$.ajax的设置合并)

第3版

另一种选择:将链接的id作为附加设置键:

'idOfLink'=>'js:$(this).attr("id")',
'beforeSend'=>'function(){
     // now you can access the id like:
     console.log(this.idOfLink);// or alert(this.idOfLink)
}'

如果您使用jQuery,您可以这样做来获得元素属性:$("#element_id").attr("id"),或者如果您使用的是HTML5,您可以在链接上使用data标记,如:

<a href="bla.php" data-name="your_data_here">Link</a>

使用jQuery也可以这样做:$("#element_id").data("name")

您可能需要详细说明更多/发布代码片段,以便我们能够更好地了解您的问题。但根据您在这里的解释,我假设您希望处理Ajax请求的任何操作都能知道它是由哪个链接发起的。假设异步处理是在其他地方(浏览器之外)进行的,它就无法访问您的DOM。因此,您需要在ajax请求中嵌入id作为参数。换句话说,将发送请求的元素的id作为请求的一部分进行传递。