Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

jquery - Ajax response inside a div

I am trying to show the value of ajax response inside a div and for that I have the following code in my view file.

<script type="text/javascript" src="MY LINK TO JQUERY"></script>

<script  type="text/javascript">
     $(function(){ // added
     $('a.vote').click(function(){
         var a_href = $(this).attr('href');

     $.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>contents/hello",
            data: "id="+a_href,
            success: function(server_response){
                             if(server_response == 'success'){
                                  $("#result").html(server_response); 
                             } 
                             else{
                                  alert('Not OKay');
                                 }

                      }
  });   //$.ajax ends here

  return false
    });//.click function ends here
  }); // function ends here
 </script>

  <a href="1" title="vote" class="vote" >Up Vote</a>
  <br>
  <div class="result"></div>                                        

my Controller (to which the ajax is sending the value):

function hello() {
              $id=$this->input->post('id');
              echo $id;
             }      

Now what I am trying achieve is get the server_response value (the value that is being sent from the controller) in side <div class="result"></div> in my view file.

I have tried the following code but its not showing the value inside the div.

Could you please tell me where the problem is?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that you have mixed arguments of Ajax success handler. First goes data which your script gives back, then goes textStatus. Theoretically it can be "timeout", "error", "notmodified", "success" or "parsererror". However, in success textStatus will always be successful. But if you need to add alert on error you can add error handler. And yes, change selector in $("#result") to class. So corrected code may look like this:

$.ajax({
    type: "POST",
    url: "<?php echo base_url(); ?>contents/hello",
    data: "id=" + a_href,
    success: function(data, textStatus) {
        $(".result").html(data);    
    },
    error: function() {
        alert('Not OKay');
    }
});?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...