php 已解决-使用删除按钮和复选框从数据库中删除值-语法错误,JSON格式错误

fbcarpbf  于 2023-01-24  发布在  PHP
关注(0)|答案(2)|浏览(84)

我正尝试通过使用我在复选框输入中存储为value=""的ID来删除数据......我的想法是删除单个框/表,还是多个......是ID在输入中的存储方式有问题,还是删除功能完全错误,我没有主意了......
编辑:我设法通过在delete方法中所做的更改来解决这个问题,我在这个编辑中更正了这一点...
我已经完全重做了delete.php部分,试图找出原因,现在我得到了此负载val%5B%5D=339,并且收到了以下警报{"readyState":4,"responseText":"","status":200,"statusText":"OK"}
删除功能..

$query = "DELETE FROM `$this->table` WHERE id = ?";
  $stmt = $this->conn->prepare($query);

  $rows_deleted = 0;

  foreach ($ids as $id) {
    $stmt->bindValue(1, $id, PDO::PARAM_INT);

    $stmt->execute();

    $rows_deleted += $stmt->rowCount();
  }

  return json_encode(['rows_deleted' => $rows_deleted]);

删除. php

header('Access-Control-Allow-Origin: *');
                    header('Content-Type: application/x-www-form-urlencoded');
                    header('Access-Control-Allow-Methods: DELETE');
                    
                    
                    include_once '../../config/database.php';
                    include_once '../../models/post.php';
                    
                    //Instantiate db
                    
  $database = new Database();
$db = $database->connect();
$table = 'skandi';
$fields = [];

//Instantiate post
$product = new Post($db,$table,$fields);
$json = json_decode(file_get_contents("php://input"), true);

$product->id = $json['id'];

try {
  $response = $product->delete($product->id);
  echo $response;
} catch (\Throwable $e) {
  echo "Error occurred in delete method: " . $e->getMessage();
}

具有输入的表...

async function renderUser() {
        let users = await getUsers(); 
        let html = ``;

        users.forEach(user => {
            let htmlSegment = `
                <table class="box">
                    <tr> 
                    <th> <input type='checkbox' id='checkbox' name='checkbox[]' value=${user.id}> </th>                                           
                    <td>  ${user.sku}</td>
                    <td>  ${user.name}</td>
                    <td>  ${user.price}</td>
                    ${user.size ? `<td> Size: ${user.size} $ </td>` : ""} 
                    ${user.weight ? `<td> Weight: ${user.weight}  Kg</td>` : "" }
                    ${user.height ? `<td>  Height: ${user.height} CM</td>` : ""}
                    ${user.length ? `<td>  Length: ${user.length} CM</td>` : ""}
                    ${user.width ? `<td>  Width: ${user.width} CM</td>` : ""}
                    </tr>
                </table>`;

                html += htmlSegment;
        });

        let container = document.querySelector('.message');
        container.innerHTML = html;
    }
    renderUser();
  };

AJAX 删除请求

$(document).ready(function () {
  $("#deleteBtn").click(function (e) {
    
    let checkboxes = document.querySelectorAll("input[type=checkbox]:checked");

    let ids = [];

    for (let checkbox of checkboxes) {
      ids.push(checkbox.value);
    }
    // Create the query string using the IDs array
    // let queryString = '?' + ids.map((id) => `id=${id}`).join('&');
    let data = {
      id: ids,
    };
    $.ajax({
      url: "/api/post/delete.php",
      type: "DELETE",
      data: JSON.stringify(data),
      dataType: "json",
      contentType: "application/json",
      success: function (response) {
        console.log(response);
      },
      error: function (error) {
        console.log(error);
      },
    });
  });
});
7kqas0il

7kqas0il1#

header('Content-Type: application/json');更改为header('Content-Type: application/x-www-form-urlencoded');
对于删除请求,它需要声明application/x-www-form-urlencoded头,因为HTML不支持DELETE方法,我们人为地使用它。
希望这对你和其他人在未来有帮助:)

lo8azlld

lo8azlld2#

$.ajax({
    type:'POST',
    url:'delete.php',
    data:{del_id:del_id},
    success: function(data){
         if(data=="YES"){
             $ele.fadeOut().remove();
         }else{
             alert("can't delete the row")
         }
    }

     })
})

相关问题