简体   繁体   中英

How to display ajax response to HTML in code igniter

I need to display the json data that i receive from ajax request to html

In alert i am getting the json data

Here is my view

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

   //need to display the results that i fetch from ajax request

  <?php }? >
   }

Here is my jquery

$('.testing').click(function() {

$.ajax({
    url : "path_to_your_controller",
    data: {
        id: $(this).data("index")
    },
    type: "POST"
    success: function(data)
    {
        alert(data);
    },

});

Here is my controller

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

Set ajax dataType: "json" get json data in success:function(data, textStatus, jqXHR) as specified below

$.ajax({
        url : "path_to_your_controller",
        dataType: "json",
        data: {
            id: $(this).data("index")
        },
        type: "POST"
        success: function(data, textStatus, jqXHR)
        {
            // here json data you want
            alert(data.value);
            alert(data.value2); // as key set in json array in controller
            console.log('success');
            console.log(data);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
          console.log('we are in error');
        }
    });

Nothing to do here with the codeigniter. All you need to do is on the client side. Try this:

$.ajax({
   url : "path_to_your_controller",
   data: {
    id: $(this).data("index")
   },
  type: "POST"
  success: function(data)
  {
    $(data).each(function(index,value)){
    html += '<a>'+value+'</a>';
   }
   $('class or id name').append(html);
  },
});

Or you can simple write console.log(data.key_name) like data.value1 in order to get the data.

Edit: Don't foget to add var html = '' at the start. Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM