Javascript 如何在单击cakephp时使用ajax更改状态
我还想在单击它们时更改状态消息。这是我想申请的图像 如图所示,当我单击它时,活动状态需要更改为非活动状态。我可以用“编辑页面”进行编辑,但现在我想在页面加载时单击“活动”来更改状态。这是我的代码ctp文件Javascript 如何在单击cakephp时使用ajax更改状态,javascript,php,jquery,ajax,cakephp,Javascript,Php,Jquery,Ajax,Cakephp,我还想在单击它们时更改状态消息。这是我想申请的图像 如图所示,当我单击它时,活动状态需要更改为非活动状态。我可以用“编辑页面”进行编辑,但现在我想在页面加载时单击“活动”来更改状态。这是我的代码ctp文件 <td class="center"> <?php if($listings['status']=="1") { ?> <span class="label label-success">Active</spa
<td class="center">
<?php if($listings['status']=="1") { ?>
<span class="label label-success">Active</span>
<?php } else if($listings['status']=="0") {?>
<span class="label label-error">Inactive</span>
<?php } ?>
</td>
请帮助我,告诉我如何使用ajax或jquery来实现这一点。您实际上可以做到如下简单:
$("body").on("click", "#status", function(e) {
e.preventDefault();
var stat = find("span#span_id").val(); // get the status current value
$.get('./db_file', function(data) {
if (data.stat != stat)
$("#span_id").removeClass("label label-error").addClass("label label-success");
}, "json");
});
类似的方法也行。试试这个:
HTML: <button type="button" class="active" data-id="2">Active/button>
//Note that data-id ...It's just an attribute I created, and the value "2" I //believe will be dynamic in your case -Probably that college ID in the DB
最后但并非最不重要的一点是您的路线:
Router::connect('/changeStatus', array('controller' => 'yourcontroller', 'action' => 'changeStatus'));
希望这能有所帮助。
祝您好运我想根据数据库值更改状态。单击“活动”后未工作,未执行任何操作。请勿复制粘贴代码,请自行创建。用目录替换
”./db_文件“
,并在span标记上分配id
<script>
$(document).on('click', 'button[data-id]', function(event) {
event.preventDefault();
var collegeID = $(this).attr('data-id');
$.ajax({
url: 'changeStatus',
type: 'POST',
dataType: 'json',
data: {id: collegeID},
success: function(data){
if (data['status'] == "success") {
$('button[data-id]').removeClass('active').addClass('inactive');
/*Class active and inactive should be in your CSS with color according to their names*/
};
}
});
});
</script>
public function changeStatus(){
$this->autoRender = false;
if ($this->request->is('ajax')) {
$data = $this->request->data;
/*The id that was passed thru data-id attribute is here: */
//$data['id'] Use it to update your DB
//After successful update
$response = array('status' => 'success');
return json_encode($response);
}
}
Router::connect('/changeStatus', array('controller' => 'yourcontroller', 'action' => 'changeStatus'));