CodeIgniter控制器 - JSON - AJAX

问题描述 投票:3回答:3

我正在尝试通过AJAX发送带有CodeIgniter的表单构建,并尝试使用JSON获取响应。但是,当我打开我的开发人员选项卡时,我只看到响应(我甚至不确定,如果这实际上是一个响应,因为它显示了两个json数据)。

它显示的只是加载微调器,然后消失。

代码已在不使用AJAX的情况下进行了测试,并且可以正常运行,因此PHP中不会出现错误。

这是我的重置密码的控制器:

<?php

Class Users extends CI_Controller {

    public function forgot_pass()
    {

    if(!$this->input->post('to_email'))
    {
    exit("No data");
    }


    $this->load->model('user');
    $email = $this->input->post('to_email');
    $email_addr = $this->user->get_email_address($email);


    if(empty($email_addr))
    {
    echo json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try  again"));
    }

    $this->load->helper('string');
    $new_password = random_string('alnum', 8);
    $this->load->library('phpass'); 

    $update_password = array( 'password' => $this->phpass->hash($new_password));
    $update_password = $this->user->update_password($email, $update_password);

    $this->load->library('email');

    $config['newline'] = '\r\n';
    $this->email->initialize($config);

    $this->email->from('[email protected]', 'Your Name');
    $this->email->to($email);  
    $this->email->subject('New password');
    $this->email->message("Hey, " .$email_addr['name']. ". Your new password is: " .$new_password); 

    if($this->email->send())
    {
    echo json_encode(array('pls'=>1, 'msg' => "Password has been sent to given e-mail address"));
    }


}

}
?>

这是我用jQuery编写的AJAX调用:

$(document).ready(function() {

$("form#forget_pass_form").on('submit', function(e){

            e.preventDefault();

                $("#loading_spinner").show();
                var from = $(this);

                $.ajax({

                    url: from.attr('action'),
                    type: from.attr('method'),
                    data: $(from).serialize(),
                    }).done(function(data) {



                    if(data.pls == 0) {

                        $("#forgot-pass-success").hide();
                        $("#forgot-pass-error").show();
                        $("#forgot-pass-error").fadeIn(1000).html(data.msg);

                      }

                    if(data.pls == 1) {

                        $("#forgot-pass-error").hide();
                        $("#forgot-pass-success").show();
                        $("#forgot-pass-success").fadeIn(1000).html(data.msg);
                      }

                   $("#loading_spinner").hide(); 

                });

            return false;

        });
});
php jquery ajax json codeigniter
3个回答
10
投票

首先,您可以尝试在Controller中设置正确的标头吗?

header('Content-Type', 'application/json');

或者更好的是:

$this->output->set_content_type('application/json');

作为旁注,您应该确保始终返回JSON数据,因此我将删除exit()消息并在方法的底部放置一个默认的JSON响应。

不要忘记,当您回显JSON时,您可以在之后放置return;以停止在该方法中运行的更多代码。


2
投票

你的大多数代码都没问题。但是你需要在你的js和控制器中改变一些行。

更改1(在Ajax函数中)

更改您的ajax功能并添加dataType: "json"选项

    $.ajax({
           url: from.attr('action'),
           type: from.attr('method'),
           dataType: "json",
           data: $(from).serialize(),
          }).done(function(data) {

           ....

        });

更改2(在控制器中)

退出(“无数据”);

exit(json_encode(array('pls'=> 0,'msg'=>“No data”)));

更改3(在控制器中)

echo json_encode(array('pls'=> 0,'msg'=>“找不到电子邮件地址。再试一次”));

exit(json_encode(array('pls'=> 0,'msg'=>“找不到电子邮件地址。再试一次”)));

说明

  1. 第一个更改告诉您的脚本以Json的形式处理响应数据
  2. 第二个更改是保持所有返回类型相同,如果不是,当您只发送no data响应时,您没有从yous js处理此选项。
  3. 最后一次更改确保在发送电子邮件失败时停止进一步处理,并停止显示两个json。

0
投票

我想建议你关于json回归。首先在你的ajax你必须使用dataType: 'json'

$.ajax ({
        url: from.attr('action'),
        type: from.attr('method'),
        data: $(from).serialize(),
        dataType: 'json',
    }).done(function(data) {

           ..your code..

    });

CodeIgniter有output类,为什么不使用output类来响应来自CI的ajax。

$output = array('pls' => 1,
                'msg' => "Password has been sent to given e-mail address"
          );
$this->output->set_content_type('application/json')
             ->set_output(json_encode($output));

使用output类,这比echo更有效

我希望它能帮助你获得更好的代码风格。

© www.soinside.com 2019 - 2024. All rights reserved.