【发布时间】:2023-03-31 13:17:01
【问题描述】:
我使用模态删除json文件数据删除。但我使用 JavaScript 将我的 json 文件数据查看到 html 文件中。但我使用删除模式来删除无法正常工作的数据。现在我曾经在没有任何警告信息的情况下删除数据。这是我查看数据的 JavaScript 代码。
var output = document.getElementById('output');
var ajaxhttp = new XMLHttpRequest();
var url = "form.json";
var xhttp = new XMLHttpRequest();
var details = '';
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//var response = JSON.parse(xhttp.responseText);
var response = JSON.parse(xhttp.responseText);
var output = '';
output += "<table class='table table-bordered'>";
output += "<tr><th scope='col'>id</th><th>First Name</th><th>Last Name</th><th>Age</th><th>Action</th></tr>";
for(x in response){
if(response[x].is_active == "1"){
output += "<tr><td>" + response[x].id + "</td><td>" + response[x].firstname + "</td><td>"+response[x].lastname+"</td><td>"+response[x].age+"</td><td><a href='edit.php?id="+response[x].id+"&firstname="+response[x].firstname+"&lastname="+response[x].lastname+"&age="+response[x].age+"' class='btn btn-primary btn-sm active' role='button' aria-pressed='true'>Edit</a><a href='update.php?id="+response[x].id+"&firstname="+response[x].firstname+"&lastname="+response[x].lastname+"&age="+response[x].age+"' class='btn btn-danger btn-sm' role='button' name='btnDelete' style='margin-left: 10px;'>Delete</a></td></tr>";
}
}
output += "</table> ";
document.getElementById("output").innerHTML = output;
这是我的删除 php 函数来更新活动状态。
session_start();
$success = "<div class='alert alert-danger' role='alert'>User Deleted Successfully</div>";
$success = urlencode($success);
$myFile = "form.json";
//create empty array
$arr_data = array();
try{
//Get form data
$formdata = array(
'id' => $_GET['id'],
'firstname' => $_GET['firstname'],
'lastname' => $_GET['lastname'],
'age' => $_GET['age'],
'is_active' => '0'
);
//get data from existing json file
$jsondata = file_get_contents($myFile);
//converts json data into array
$arr_data = json_decode($jsondata, true);
$updateKey = null;
foreach($arr_data as $key=>$value){
if($value['id'] == $formdata['id']){
$updateKey = $key;
}
}
if($updateKey === null){
array_push($arr_data, $formdata);
}
else{
$arr_data[$updateKey] = $formdata;
}
//push user data to array
//array_push($arr_data, $formdata);
//convert update array to json
$jsondata = json_encode($arr_data);
//write json data into form.json file
if(file_put_contents($myFile, $jsondata)){
header("location: index.php?success=$success");
}else{
echo "error deleting";
}
}
catch(Exception $e){
echo 'Caught Exception ', $e->getMessage(), "\n";
}
我如何使用模型调用此 php 函数以使用 JavaScript 按钮删除数据。
【问题讨论】:
-
您检查过您的开发控制台是否有错误?
-
我想将我的删除按钮操作传递给一个模态并将其发送到我的 update.php 文件以删除数据
-
我尝试过使用模态。但它不起作用
-
PHP 部分与 JS 部分不适合。 JS 正在等待一个 JSON 字符串,但 PHP 从不发送它。当数据成功保存时,您应该回显
$jsondata,而不是设置 Location 标头。
标签: javascript php json