【问题标题】:CodeIgniter Controller - JSON - AJAXCodeIgniter 控制器 - JSON - AJAX
【发布时间】:2014-06-01 03:24:50
【问题描述】:

我正在尝试通过 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('your@example.com', '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;

        });
});

【问题讨论】:

  • 在 $.ajax dataType 中丢失,请在 $.ajax 调用中添加 dataType: 'JSON';也可以使用 die 或 exit 来停止脚本的执行

标签: php jquery ajax json codeigniter


【解决方案1】:

首先,您可以尝试在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("没有数据");

exit(json_encode(array('pls'=>0, 'msg' => "无数据")));

更改 3(在控制器中)

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

exit(json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try again")));

解释

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

【讨论】:

    【解决方案3】:

    我想建议你关于 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效率更高

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

    【讨论】:

      猜你喜欢
      • 2013-02-24
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      • 2019-06-14
      • 2012-12-26
      相关资源
      最近更新 更多