Bry*_*arn 24 javascript php codeigniter
如何将控制器的响应返回给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;
});
Run Code Online (Sandbox Code Playgroud)
数据返回null(空白)!
function onSuccessRegistered(data){
alert(data);
};
Run Code Online (Sandbox Code Playgroud)
控制器 -
public function signin() {
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode( $arr );
}
Run Code Online (Sandbox Code Playgroud)
小智 72
return $this->output
->set_content_type('application/json')
->set_status_header(500)
->set_output(json_encode(array(
'text' => 'Error 500',
'type' => 'danger'
)));
Run Code Online (Sandbox Code Playgroud)
Sun*_*dar 39
//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 );
}
Run Code Online (Sandbox Code Playgroud)
对于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);
}
}
Run Code Online (Sandbox Code Playgroud)
就我而言,我使用的是 ci4 ,我向 clinet 发送响应,如下所示:例如在 App\Controllers\Category:setOrder 中,我的类别控制器扩展了BaseController
return $this->response->setJson(['msg'=>'update-success']);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
97594 次 |
最近记录: |