我有一个简单的应用程序在codeigniter。在我看来,我向控制器发出了ajax POST请求,但我没有接收到响应数据。我检查了网络选项卡中的chrome dev工具,响应消息是:此请求没有可用的响应数据:我的视图:
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>First</td>
<td>Sec</td>
<td>Th</td>
<td>Th</td>
</tr>
</thead>
<tbody>
<?php
if(isset($result))
{
foreach($result as $value)
{
echo "<tr><td>". $value->cai . "</td><td>". $value->partner ."</td><td>". $value->spot ."</td><td><button type='button' id='".$value->cai."' class='btn btn-danger delete'>Delete</button></td></tr>";
}
}
?>
</tbody>
</table>
<?php echo $this->pagination_bootstrap->render(); ?>
<script>
$('.table').on('click','.delete',function(){
var id=$(this).attr('id');
var confirm_box=confirm('Sure?');
if(confirm_box === true)
{
$.ajax({
url: '<?php echo site_url('Tires_Crud/deleteCai'); ?>',
type: 'POST',
data: {
key: id
},
dataType: 'json',
success: function(data) {
console.log(JSON.parse(data));
}
});
}
});
</script>我的控制器:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Tires_Crud extends MY_Controller
{
public function deleteCai()
{
$status = array(
"STATUS" => "true"
);
return json_encode($status);
}
}在我的配置文件中,CSRF保护被禁用!因为当它被启用时,ajax请求就不工作了。提前感谢您的帮助!
发布于 2021-06-10 03:41:46
这段代码有一些问题。
#1:形成ajax请求的方式。其中的type: 'POST'应该是method: 'POST' -但不仅仅是一个拼写错误,重要的是要理解这些方法被称为HTTP 方法-与在<form method='post'标记中指定的方式相同。如果不提供method,则假定为GET。
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
另外,由于您指定了dataType:'json' - jquery将提供一个可以使用的已解析JSON对象。你不需要自己去解析它
$.ajax({
url: '<?php echo site_url('Tires_Crud/deleteCai'); ?>',
method: 'POST', // <-- change this from 'type' to 'method'
data: {
key: id
},
dataType: 'json',
success: function(data) {
// console.log(JSON.parse(data)); // <-- no need to parse - you have set dataType to be json, which means it will come to you already parsed
console.log(data);
})#2 -在你的PHP中,你会用$_POST['key']捕获你的key变量(你在ajax中发送的)-尽管在codeigniter中你会得到这样的结果:
// codeigniter 2.x and 3.x
$this->input->post('key');
// codeigniter 4
use CodeIgniter\HTTP\IncomingRequest;
$request = service('request');
$request->getPost('key');#3 -使用ajax,你实际上是echo响应,而不是return它:
public function deleteCai(){
$status = array(
"STATUS" => "true"
);
echo json_encode($status);
}https://stackoverflow.com/questions/67910259
复制相似问题