13

我试图在 div 中显示 ajax 响应的值,为此我在我的视图文件中有以下代码。

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

我的控制器(ajax 向其发送值):

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

现在我要实现的是<div class="result"></div>在我的视图文件中获取 server_response 值(从控制器发送的值)。

我已经尝试了以下代码,但它没有显示 div 内的值。

你能告诉我问题出在哪里吗?

4

3 回答 3

13

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');
    }
});​
于 2012-05-13T23:17:08.170 回答
6
success: function(server_response) {
        $(".result").html(server_response);
}​

<div class="result"></div> // result is the class

.result选择器不应该#result

于 2012-05-13T23:13:15.843 回答
1

尝试更改<div class="result"></div><div id="result"></div>,因为这是您在 ajax 成功函数中引用的内容

$("#result").html(server_response);

于 2012-05-13T23:12:38.613 回答