我正在使用ajax将数据发送到PHP
脚本并在数据库中设置查询。我的代码:
HTML脚本 :
<span id="btn_span_<?php echo $user_id ?>">
<?php if ($online == 1) { ?>
<button onclick="update_online(1,<?php echo $user_id; ?>,'btn_span_<?php echo $user_id ?>')" class="btn-custom-delete btn btn-status">is active</button>
<?php } elseif ($online == 0) { ?>
<button onclick="update_online(0,<?php echo $user_id; ?>,'btn_span_<?php echo $user_id ?>')" class="btn-custom-services btn btn-status">active
</button>
<?php } ?>
</span>
JAVASCRIPT脚本 :
function update_online(status, id, span_id) {
var settings = {
"async": true,
"crossDomain": true,
"url": "script_edit_status.php?status=" + status + '&id=' + id + '&span_id=' + span_id,
"method": "GET"
};
$.ajax(settings).done(function (response) {
var obj = JSON.parse(response);
var btn = document.getElementById(span_id);
if (obj.status == "1") {
btn.innerHTML = "<button onclick='update_online(1,obj.id,obj.span_id)' class='btn-custom-services btn btn-status'>active</button>";
} else if (obj.status == "0") {
btn.innerHTML = "<button onclick='update_online(0,obj.id,obj.span_id)' class='btn-custom-delete btn btn-status'>is active</button>";
}
});
}
PHP脚本 :
<?php
include_once "../db/connection.php";
$id = $_GET['id'];
$status = $_GET['status'];
$span_id = $_GET['span_id'];
try {
if ($status == 1) {
$sql_edit_status = "update api_user set online=0 where id='$id';";
} elseif ($status == 0) {
$sql_edit_status = "update api_user set online=1 where id='$id';";
}
$conn->query($sql_edit_status);
$status_arr = array(
"id" => $id,
"status" => $status,
"span_id" => $span_id
);
echo json_encode($status_arr);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
可以执行第一个操作,但是当我想单击second time
的按钮时,consol显示以下错误:
未捕获的ReferenceError:未定义obj
该错误是由于innerHTML无法正确发送方法而引起的...
你能帮我吗?
答案 0 :(得分:0)
btn.innerHTML = "<button onclick='update_online(0," + obj.id + "," + obj.span_id + ")' class='btn-custom-delete btn btn-status'>is active</button>";