如何在代码点火器中将锚标记的数据索引值传递给控制器


How to pass data-index value of anchor tag to controller in code igniter

我需要将锚标记的data-index值传递给CodeIgniter中的控制器。

这是我的观点:

<?php for ($i=0; $i<5; $i++){?>
<a href="#" class='testing' data-index="<?= $i;?>" >testlink</a>
 //need to display the json data i am recieving from jquery here 
<?php }? >
}

这是JQuery:

$('.testing').click(function() {
    $.ajax({
        url : "path_to_your_controller",
        data: {
            id: $(this).data("index")
        },
        type: "POST"
        success: function(data, textStatus, jqXHR)
        {
            console.log('success');
            console.log(data);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
          console.log('we are in error');
        }
    });

这是我的控制器

         $data= array('value' =>22,
                        'value2'       => 32,
                        'value3'       => 'foo',
                        'value4'       =>  'bar',
                        'value5'       => '122',

                );

echo json_encode($data);

如何在php 中显示来自ajax请求的json数据

你可以试试这样的东西:

<?php for ($i=0; $i<5; $i++){?>
    <a href="#" class='testing' data-index="<?= $i;?>" >testlink</a>
<?php }? >

然后AJAX:

 $('.testing').click(function() {
        $.ajax({
            url : "path_to_your_controller",
            data: {
                id: $(this).data("index")
            },
            type: "POST"
            success: function(data, textStatus, jqXHR)
            {
                console.log('success');
                console.log(data);
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
              console.log('we are in error');
            }
        });

您必须使用类,而不是通过id调用函数

查看文件代码

<?php
for ($i=0;$i<5;$i++){
?>
    <a href="#"  id="testing_<?php echo $i;?>" class="testing" data-index="<?php echo $i;?>">testlink</a>
<?php
}
?>

您的脚本//将dataType传递为json

$('.testing').click(function() {
        var a = $(this).data("index"); 
        $.ajax({
            type: "POST",
            dataType: "json",
            url: 'url to controller',
            data: {id:a},
            success: function(result) {
                // you can get here the result the result of ajax request.
                // get each value as key.value( of controller ).
                alert(result.value);
            },
            error: function(a,s,d) {
                console.log('error');
            } 
        });
    });

在您的控制器中获取此id作为

// in controller function get id as like
$this->input->post('id');