使用动态链接触发ajax [英] Using dynamic links to trigger ajax

查看:58
本文介绍了使用动态链接触发ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个链接,我想通过这些链接通过ajax触发操作,但是我不知道如何继续处理此问题.我已经解决了静态链接的问题,但是我的链接是动态的,并且在不同的阶段会有不同数量的链接.

I have a couple of links that I want to trigger operations through ajax from, but I dont know how to continue on this matter. I've kind of solved it for static links but my links are dynamic and there will be different amount of links at different stages.

我有一个如下所示的index.php:

I have a index.php that looks like this:

<script src="../jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function() {
  $("#link1").click(function(e) {
     e.preventDefault();
     $('#result').empty().text('Executing command...'); 
     $('#result').load('ajax.php?op=edit&id=4', function(){         
        $('#result').before("The server answered:");
        $('#result').after("The operation was a success<br>");
    }); // end load
  }); //end click
}); //end ready()
</script>

<div id='result'></div>
<a id='link1' href='#'>Link 1</a><br>
<a id='link2' href='#'>Link 2</a><br>
<a id='link3' href='#'>Link 3</a><br>
<a id='link4' href='#'>Link 4</a><br>
<a id='link5' href='#'>Link 5</a><br>
<a id='link6' href='#'>Link 6</a><br>

"ajax"文件如下所示:

And the "ajax" file looks like this:

<?php
if(isset($_GET['op']) && isset($_GET['id'])) {
    $op = $_GET['op'];
    $id = $_GET['id'];
    switch($op) {
        case "edit":
            // do operations here
            echo $id;
            break;
        case "doSomethingElse":
            // do other operations here
            echo $id;
            break;
    }
}
?>

所以我现在遇到的问题是:我该如何解决这个问题,这样就不必在jquery ready()函数中定义每个链接了?

So what I struggle with now is: How do I solve this so I don't have to define each link within the jquery ready() function?

基本上,我需要根据我单击的链接来触发ajax.php文件中的操作.

Basicly I need to trigger an operation in the ajax.php file depending on what link I click.

有什么想法吗?

推荐答案

尝试使用此选择器;

$('[id^="link"]')

$(document).ready(function() {
  $('[id^="link"]').click(function(e) {
     e.preventDefault();
     $('#result').empty().text('Executing command...'); 
     $('#result').load('ajax.php?op=edit&id=4', function(){         
        $('#result').before("The server answered:");
        $('#result').after("The operation was a success<br>");
    }); // end load
  }); //end click
}); //end ready()

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id='result'></div>
<a id='link1' href='#'>Link 1</a><br>
<a id='link2' href='#'>Link 2</a><br>
<a id='link3' href='#'>Link 3</a><br>
<a id='link4' href='#'>Link 4</a><br>
<a id='link5' href='#'>Link 5</a><br>
<a id='link6' href='#'>Link 6</a><br>

这篇关于使用动态链接触发ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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