php CodeIgniter 控制器 - JSON - AJAX

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23123271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:30:52  来源:igfitidea点击:

CodeIgniter Controller - JSON - AJAX

phpjqueryajaxjsoncodeigniter

提问by B_CooperA

I'm trying to send a form build with CodeIgniter via AJAX and trying to get the response with JSON. However, I only see the respond when I open my developer tab (I'm not even sure, if that's actually a respond since it's showing both of the json data's).

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

All it shows, is the loading spinner, and after that it vanishes.

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

Code have been tested without AJAX and it works, so there can't be errors in PHP.

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

Here's my controller for resetting the password:

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

<?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"));
    }


}

}
?>

And here's my AJAX call written with jQuery:

这是我用 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;

        });
});

回答by Andy02

Firstly, can you try setting the correct header in the Controller?

首先,您可以尝试在控制器中设置正确的标题吗?

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

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

Or better yet:

或者更好:

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

As a side note, you should make sure you are always returning JSON data, so I would remove the exit()message and put a default JSON response at the bottom of the method.

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

Don't forget, when you echo your JSON, you can put return;afterwards to stop any more code running afterwards in that method.

不要忘记,当你回显你的 JSON 时,你可以 put return;after 停止在该方法中运行的任何更多代码。

回答by B_CooperA

Most of your code is ok. But you need to change some lines, both in your js, and controller.

你的大部分代码都没问题。但是您需要在 js 和控制器中更改一些行。

Change 1(In Ajax function)

变化 1(在 Ajax 函数中)

Change your ajax function and add dataType: "json"option

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

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

           ....

        });

Change 2 (In controller)

变化 2(在控制器中)

exit("No data");

exit("没有数据");

to

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

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

Change 3 (In controller)

变化 3(在控制器中)

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

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

to

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

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

explanation

解释

  1. First change tell your script to handle the response data as Json
  2. Second change is to keep all your return type same, if not when you sending only the no dataresponse you are not handling this option from youe js.
  3. And the last change make sure you stop further processing when sending email fails, and stop from showing both json.
  1. 第一个更改告诉您的脚本将响应数据处理为 Json
  2. 第二个变化是保持所有的返回类型相同,如果不是,当你只发送no data响应时,你不会从你的 js 处理这个选项。
  3. 最后一个更改确保您在发送电子邮件失败时停止进一步处理,并停止同时显示 json。

回答by Ian Patel

I would like to suggest you about json return. First in your ajax you have to use dataType: 'json'

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

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

           ..your code..

    });

CodeIgniter have outputclass, why don't you use outputclass to respond to ajax from CI.

CodeIgniter 有output类,你为什么不使用output类来响应来自CI.

$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));

Use outputclass, this is more efficient then echo

使用output类,这样效率更高echo

I hope it will helps you for better code style.

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