AJAX解析数据和更改类的链接列表


List of links with AJAX parsing data and changing class

我已经尝试了很多不同的方法来实现这一点,但还没有找到正确的方法来解决这个问题。

我需要制作一个链接列表,每个链接都包含许多带数据的查询字符串。我需要这些数据通过AJAX"get.php"。除了使用"get.php"中的数据外,我还希望能够通过php更改单击的特定链接的类别——例如,从"noshow"更改为"inattenance"或第三个选项链接"sick"。

我正在考虑列出这样的链接:

<a href="get.php?athlete=57&session=142" class="noshow">Athlete 1</a>
<a href="get.php?athlete=45&session=142" class="noshow">Athlete 2</a>
<a href="get.php?athlete=23&session=142" class="noshow">Athlete 3</a>

或者数据应该在ID中,以便在脚本中更好地识别?:

<a href="#" id="57&142" class="noshow">Athlete 1</a>
<a href="#" id="45&142" class="noshow">Athlete 2</a>
<a href="#" id="23&142" class="noshow">Athlete 3</a>

AJAX是否能够根据ID更改链接,或者每个链接都需要在DIV中?

我很想得到一些关于从这里去哪里的帮助!

提前感谢!

如果我理解您试图正确地做什么,那么您应该使用像jQuery这样的JavaScript库来帮助您做到这一点。

// bind a click handler to all links that have href starting with get.php
$("a[href^=get.php]").on("click", function(e){
    // prevent link from navigating to get.php
    e.preventDefault();
    // jQuery object of the anchor tag
    var $link = $(this);
    // use Ajax to send data to get.php
    $.getJSON($link.attr("href"), function(data){
        // replace current class with the value in data.class
        $link.removeClass().addClass(data.class);
    });
})

get.php应返回json数据

header('Content-Type: application/json');
echo json_encode(array(
    'class' => 'new class',
));
  1. 捕捉点击功能
  2. 创建对触发单击的元素的引用
  3. 执行ajax,并将url替换为我们单击的元素的href
  4. 将响应类型设置为JSON(以便在成功函数中自动解析)
  5. 比较类属性是否有null响应,如果没有,则添加从脚本返回的类

jQuery:

$(function(){
    $('a').click(function(e){
        e.preventDefault(); // stop the default action from taking you to get.php
        var $this = $(this); //cachable reference because $(this) inside the $.ajax() does not refer to the "A" we clicked on
        $.ajax({
            url: $this.prop("href"), //will pass the data, default is $_GET anyway
            dataType: 'json', //so we can easily access the class (if we need) and then the raw data.
            success: function(data){
                if(data.class != null){
                     $this.addClass(data.class); //add the class from the php script return
                }
                //do something with data.body which is the rest of the code
            }
        });
    });
});

然后在PHP脚本中,只需返回一个带有预期键的json数组。

echo json_encode(array(
    'class' => 'inactive',
    'body' => 'whatever you were returning before'
));