36

如何将控制器的响应返回给 Jquery Javascript?

Javascript

$('.signinform').submit(function() { 
   $(this).ajaxSubmit({ 
       type : "POST",
       url: 'index.php/user/signin', // target element(s) to be updated with server response 
       cache : false,
       success : onSuccessRegistered,
       error: onFailRegistered
   });        
   return false; 
}); 

数据返回 null(空白)!

function onSuccessRegistered(data){
    alert(data);
};

控制器 -

public function signin() {
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);    
    echo json_encode( $arr );
}
4

5 回答 5

88
return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode(array(
                    'text' => 'Error 500',
                    'type' => 'danger'
            )));
于 2015-02-27T10:02:29.393 回答
53
//do the edit in your javascript

$('.signinform').submit(function() { 
   $(this).ajaxSubmit({ 
       type : "POST",
       //set the data type
       dataType:'json',
       url: 'index.php/user/signin', // target element(s) to be updated with server response 
       cache : false,
       //check this in Firefox browser
       success : function(response){ console.log(response); alert(response)},
       error: onFailRegistered
   });        
   return false; 
}); 


//controller function

public function signin() {
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);    

   //add the header here
    header('Content-Type: application/json');
    echo json_encode( $arr );
}
于 2013-09-16T06:30:34.303 回答
3

对于CodeIgniter 4,您可以使用内置的API Response Trait

以下是供参考的示例代码:

<?php namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class Home extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        $data = [
            'data' => 'value1',
            'data2' => 'value2',
        ];

        return $this->respond($data);
    }
}
于 2020-10-07T19:19:50.347 回答
0

这不是您的答案,这是处理表单提交的另一种方式

$('.signinform').click(function(e) { 
      e.preventDefault();
      $.ajax({
      type: "POST",
      url: 'index.php/user/signin', // target element(s) to be updated with server response 
      dataType:'json',
      success : function(response){ console.log(response); alert(response)}
     });
}); 
于 2013-09-16T06:53:40.227 回答
0

在我的情况下,我使用的是 ci4,我像这样向 clinet 发送响应:例如在 App\Controllers\Category:setOrder 我的类别控制器扩展BaseController

  return $this->response->setJson(['msg'=>'update-success']);
于 2021-07-10T06:42:35.120 回答