douxianglu4370
2017-10-06 07:23
浏览 49

AJAX响应返回html内容

I have an AJAX call in my codeigniter project. Here is my code:

in view :

$('#forgotPassword').click(function() {
        var base_url = '<?php echo base_url()?>'; 
        $('#forgotPasswordEmailError').text('');
        var email = $('#forgotPasswordEmail').val(); 
        console.log(email);
        if(email == ''){
            $('#forgotPasswordEmailError').text('Email is required');
        }else{
            $.ajax({
                url : base_url + 'Home/forgotPassword',
                type : 'POST',
                data : {email : email},
                success: function(data) {       
                    console.log(data);                  
                    //location.reload();
                }
            });
        }

    });

and controller :

public function forgotPassword() { 
   $email = $this->input->post('email');
   echo $email; 
}

but the response contains only the html content from my view. I couldn't identify what is happening.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyong8071 2017-10-06 07:28
    已采纳

    change your jquery code to

    $('#forgotPassword').click(function() {
        var base_url = '<?php echo base_url()?>'; 
        $('#forgotPasswordEmailError').text('');
        var email = $('#forgotPasswordEmail').val(); 
        console.log(email);
        if(email == ''){
            $('#forgotPasswordEmailError').text('Email is required');
        }else{
            $.ajax({
                url : base_url + 'Home/forgotPassword',
                type : 'POST',
                data : {email : email},
                dataType:'json',
                success: function(data) {       
                    console.log(data);                  
                    //location.reload();
                }
            });
        }
    
    });
    

    change your controller code like

    public function forgotPassword() { 
       $email = $this->input->post('email');
       $response = ["email" => $email];
       echo json_encode($response);
    }
    
    点赞 评论
  • down00112 2017-10-06 07:26

    Instead of

    echo $email;
    

    use:

    $response = ["email" => $email];
    
    return json_encode($response);
    

    And parse JSON, on client side, using JSON.parse.

    点赞 评论

相关推荐 更多相似问题