我正在开发一个控制面板页面,用户可以在其中更改他们的服务状态。我有一个 CodeIgniter 项目,其中一个名为 activation 的函数用于更改用户状态。它为状态更改执行所有数据库更新。
HTML 文件
<html>
<head>
<script src="jquery.min.js"></script>
<script>
function activation (state)
{
$.ajax({
type: "POST",
dataType: "json",
data: {'status':state},
url: 'http://myservice.lan/cp/activation',
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
success: function(data)
{
var active = '<button onClick="activation(\'deactivate\')" >Deactivate</button>';
var inactive = '<button onClick="activation(\'activate\')" >Activate</button>';
if (data.ust == 'active')
{
$('#polo').html(active);
}
else(data.ust == 'inactive')
{
$('#polo').html(inactive);
}
}
});
}
</script>
</head>
<body>
<div id='polo'>
<button onClick="activation('activate')" >Activate</button>
</div>
</body>
</html>
PHP 函数(一个 CodeIgniter 项目)
我还没有把db相关的代码放进去
public function activation()
{
$opt=$this->input->post('status', TRUE);
if ($opt=='activate') {
$data['ust']='active';
}
if ($opt=='deactivate') {
$data['ust']='inactive';
}
echo json_encode($data);
}
我无法让它工作。状态改变一次,然后即使重复点击按钮也保持不变。
我需要有关使用更好的 jQuery 功能来自动获取状态而不是将其传递给函数的帮助。
最佳答案
您的 else 语句包含不会影响您应该使用 else if
的行为的语句。
你自己看here
function(data)
{
var active = '<button onClick="activation(\'deactivate\')" >Deactivate</button>';
var inactive = '<button onClick="activation(\'activate\')" >Activate</button>';
if (data.ust == 'active')
{
$('#polo').html(active);
}
else if(data.ust == 'inactive') // instead of else(data.ust == 'inactive')
{
$('#polo').html(inactive);
}
}
关于php - AJAX 从 PHP 响应更改 div 内容不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17832521/