donglu7286 2014-09-24 18:28
浏览 5

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

I have been trying a lot of different ways to make this work, but haven't found the right way to tackle this yet.

I need to make a list of links, each containing a number of querystrings with data. I need this data going to "get.php" through AJAX. Apart from using the data in "get.php" I would like to be able to via PHP change the class of the specific link clicked - for an example from "noshow" to "inattendance" or a third option link "sick".

I am thinking of listing the links like this:

<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>

Or perhaps the data should be in the ID to better be recognized in the script?:

<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>

Is AJAX able to change a link based on its ID, or would each link need to be inside a DIV?

I would love to get some help regarding where to go from here!

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • dsirr48088 2014-09-24 18:37
    关注
    1. Capture the click function
    2. Create a reference to the element that triggered the click
    3. Perform the ajax, and replace the url with the href of the element we clicked
    4. Set the response type as JSON (so it is automatically parsed in the success function)
    5. Compare if the class property has a null response, if not, add the class returned from the script

    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
                }
            });
        });
    });
    

    Then in your PHP script, just return a json array with the expected keys.

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

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数