dongzhazhuo0572 2019-02-01 09:46
浏览 136

如何添加应删除在站点和json文件中的删除按钮

I'm newbie in javascript and I need help. In code i need to add two delete button:

  1. delete one object created
  2. delete all objects created

This buttons need to delete object in a json file. I don't know how to write the function, please help! The code is created in html, javascript and php, and send by ajax. Objects must be deleted in the site, too.

function checkInputText(value, msg) {
    if (value == null || value == "") {
        alert(msg);
        return true;
    }
    return false;
}        
function Todo(index, part, pieces, weight) {
    this.index = index;
    this.part = part;
    this.pieces = pieces;
    this.weight = weight;
}
                      
var todos = new Array();

window.onload = init;

function init() {
    var submitButton = document.getElementById("submit");
    submitButton.onclick = getFormData;
    getTodoData();
}

function getTodoData() {
    var request = new XMLHttpRequest();
    request.open("GET", "todo.json");
    request.onreadystatechange = function() {
        if (this.readyState == this.DONE && this.status == 200) {
            if (this.responseText) { 
                parseTodoItems(this.responseText);
                addTodosToPage();
            }
            else {
                console.log("error");
            }
        }
    };
    request.send();
}

function parseTodoItems(todoJSON) {
    if (todoJSON == null || todoJSON.trim() == "") {
        return;
    }
    var todoArray = JSON.parse(todoJSON);
    if (todoArray.length == 0) {
        console.log("Error: the to-do list array is empty!");
        return;
    }
    for (var i = 0; i < todoArray.length; i++) {
        var todoItem = todoArray[i];
        todos.push(todoItem);
        addTodosToPage(todoItem);
    }
}

function addTodosToPage() {
  var table = document.getElementById("todoList");
  var tr = document.createElement("tr");
  var index = document.getElementById('index').value;
  var part = document.getElementById('part').value;
  var pieces = document.getElementById('pieces').value;
  var weight = document.getElementById('weight').value;
  tr.innerHTML = "<td>" + index + "</td><td>" + part + "</td><td>" + pieces + "</td><td>" + weight + "<td>";
  table.appendChild(tr);
}
function checkInputText(value, msg) {
    if (value == null || value == "") {
        alert(msg);
        return true;
    }
    return false;
}        

function saveTodoData() {
    var todoJSON = JSON.stringify(todos);
    var request = new XMLHttpRequest();
    var URL = "save.php?data=" + encodeURI(todoJSON);
    request.open("GET", URL);
    request.setRequestHeader("Content-Type",
                             "text/plain;charset=UTF-8");
    request.send();
}
<table>
  <thead>
    <tr>
      <th>Index</th>
      <th>Part</th>
      <th>Pieces</th>
      <th>Weight</th>
    </tr>
  </thead>
  <tbody id="todoList">
  </tbody>
</table>

<form>
  <fieldset>
    <div class="tableContainer">
      <label for="index">
        <select id="index" name="index"> 
          <option hidden="" >Index</option> 
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="5">5</option>
          <option value="6">6</option>
          <option value="7">7</option>
          <option value="8">8</option>
          <option value="9">9</option>
          <option value="10">10</option>
        </select>
      </label>
      <input placeholder="part" id="part" />
      <input placeholder="pieces" id="pieces" />
      <input placeholder="weight" id="weight" />
      <input type="button" id="submit" value="ADD" onclick="addTodosToPage()">
    </div>
  </fieldset>
</form>

<?php 

if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) { 
    function strip_slashes($input) {
        if (!is_array($input)) { 
            return stripslashes($input); 
        } else { 
            return array_map('strip_slashes', $input); 
        } 
    } 
    $_GET = strip_slashes($_GET); 
    $_POST = strip_slashes($_POST); 
    $_COOKIE = strip_slashes($_COOKIE); 
    $_REQUEST = strip_slashes($_REQUEST); 
} 
function customError($errno, $errstr) { 
    echo "<b>Error:</b> [$errno] $errstr<br>"; 
    echo "Ending Script"; 
    die("Ending Script"); 
} 
set_error_handler("customError"); 
$myData = $_GET["data"]; 
$myFile = "todo.json"; 
$fileHandle = fopen($myFile, "w"); 
fwrite($fileHandle, $myData); 
fclose($fileHandle); 

?>
</div>
  • 写回答

1条回答 默认 最新

  • douhui5529 2019-02-01 14:36
    关注

    Before I start, I'm going on a bit of a paranoid tangent and stress that the server-side PHP code you're using is not secure. For one, PHP magic quotes are deprecated and should be avoided and two, preparing the data client-side and then saving it to the server without question is a very bad idea.

    Never trust the client to format the data, otherwise I can come along and do this:

    
        var myOwnJson = [{ "data": [{
          "index":"<script>alert('You');<\/script>",
          "part":"<script>alert('Are');<\/script>",
          "pieces":"<script>alert('Not');<\/script>",
          "weight":"<script>alert('Safe');<\/script>"
          }] }];
        var URL = "save.php?data=" + encodeURI(JSON.stringify(myOwnJson));
    
    

    I'd recommend reading about input sanitization and validation. You can still build a JSON file on the client and submit it to the server but the server needs to make sure it's checking the input is as expected.

    As an example:

    <?php 
    // Try to parse read the json file as an associative array.
    $unsafe_json = json_decode( $_GET["data"], true );
    
    if( ! is_array( $unsafe_json ) ) {
        // Otherwise die, and tell the user.
        die('Failed to save');
    }
    
    // Start building a trusted json array.
    $safe_json = [ 'data' => [] ];
    
    // These are the only keys we'll accept for each todo item.
    $values = [ 'index', 'part', 'pieces', 'weight' ];
    
    foreach( $unsafe_json as $unsafe_todo ) {
        $safe_todo = [];
    
        foreach( $values as $value ) {
            if( isset( $unsafe_todo[$value] ) && is_string( $unsafe_todo[$value] ) ) {
                // Sanitize the value from the submitted json array.
                $safe_todo[$value] = filter_var( $unsafe_todo[$value], FILTER_SANITIZE_STRING );
            } else {
                // This value wasn't found in the array, we'll mark it as false.
                $safe_todo[$value] = false;
            }
        }
    
        // Add our validated todo item to the list.
        $safe_json['data'][] = $safe_todo;
    }
    
    // Save the file
    $file = fopen( "todo.json", "w" ); 
    fwrite( $file, '[' . json_encode( $safe_json ) . ']' ); 
    fclose( $file ); 
    
    

    I'm sanitizing the submitted data and removing unwanted code while validating that the submitted data is formatted the way I expect it to be.

    Going a step further, I could validate that index and weight are numeric values using FILTER_VALIDATE_INT or is_numeric which I could then whinge to the user about. Or I could sanitize those values with FILTER_SANITIZE_INT or intval to make sure those values are in a format I expect.


    But enough of the security naggage... I'll actually answer your question now.

    Without making too many changes to your current code, one way you can add a delete button or multiple delete button would be using a checkbox column. I've marked these changes in the code below, but to summarise:

    • Give each row an index and id so they can be quickly identified. Eg. <tr id="row-1"></tr>
    • I've done this by creating a global count of how many todo items there are.
    • In each row, add a checkbox, give it the value of the row's index.
    • Make a function that deletes a row based on an index parameter. Eg. removeTodo(1);
    • Make a function that loops through selected checkboxes and issue the removeTodo() function using their value.
    • Link those functions to buttons.

    // 1 ) Add a global variable to count the todo items we have.
    var todo_index = 0;
    
    function checkInputText(value, msg) {
      if (value == null || value == "") {
        alert(msg);
        return true;
      }
      return false;
    }
    
    function Todo(index, part, pieces, weight) {
      this.index = index;
      this.part = part;
      this.pieces = pieces;
      this.weight = weight;
    }
    
    var todos = new Array();
    
    window.onload = init;
    
    function init() {
      var submitButton = document.getElementById("submit");
      //submitButton.onclick = getTodoData;
      //getTodoData();
    }
    
    function getTodoData() {
      var request = new XMLHttpRequest();
      request.open("GET", "todo.json");
      request.onreadystatechange = function() {
        if (this.readyState == this.DONE && this.status == 200) {
          if (this.responseText) {
            parseTodoItems(this.responseText);
            addTodosToPage();
          } else {
            console.log("error");
          }
        }
      };
      request.send();
    }
    
    function parseTodoItems(todoJSON) {
      if (todoJSON == null || todoJSON.trim() == "") {
        return;
      }
      var todoArray = JSON.parse(todoJSON);
      if (todoArray.length == 0) {
        console.log("Error: the to-do list array is empty!");
        return;
      }
      for (var i = 0; i < todoArray.length; i++) {
        var todoItem = todoArray[i];
        todos.push(todoItem);
        addTodosToPage(todoItem);
      }
    }
    
    function addTodosToPage() {
      var table = document.getElementById("todoList");
      var tr = document.createElement("tr");
    
      // 2 ) Increment the number of todos we have by 1.
      todo_index++;
    
      // 3 ) Set the row ID to an index.
      tr.id = "todo-" + todo_index;
    
      var index = document.getElementById('index').value;
      var part = document.getElementById('part').value;
      var pieces = document.getElementById('pieces').value;
      var weight = document.getElementById('weight').value;
    
      // 4 ) Add a checkbox for selecting the row and a remove button for removing the row.
      tr.innerHTML = "\
      <td><input name='select-row' type='checkbox' value='" + todo_index + "'></td>\
      <td>" + index + "</td>\
      <td>" + part + "</td>\
      <td>" + pieces + "</td>\
      <td>" + weight + "</td>\
      <td><button onclick='removeTodo(" + todo_index + ");'>x</button><td>";
      table.appendChild(tr);
    }
    
    function checkInputText(value, msg) {
      if (value == null || value == "") {
        alert(msg);
        return true;
      }
      return false;
    }
    
    function saveTodoData() {
      var todoJSON = JSON.stringify(todos);
      var request = new XMLHttpRequest();
      var URL = "save.php?data=" + encodeURI(todoJSON);
      request.open("GET", URL);
      request.setRequestHeader("Content-Type",
        "text/plain;charset=UTF-8");
      request.send();
    }
    
    // 5 ) Add a function which will remove a todo item based on it's index.
    function removeTodo(index) {
      // Get the element.
      var row = document.getElementById('todo-' + index);
    
      // If we were able to find a row matching that id.
      if (row) {
        // Access row's parent node (tbody) and remove the row.
        row.parentNode.removeChild(row);
      }
    
      // Decrement the todo count by 1.
      todo_index--;
    }
    
    // 6 ) Add a function so we can click 'select all' to either select all rows or deselect all rows.
    function toggleSelection(checkbox) {
      // Get our rows.
      var rowsToSelect = document.querySelectorAll('input[name=select-row]');
    
      for (var i = 0; i < rowsToSelect.length; i++) {
        // Check or uncheck boxes if the 'master' checkbox is checked.
        rowsToSelect[i].checked = checkbox.checked;
      }
    }
    
    // 7 ) Add a function to remove all rows that are selected.
    function removeSelectedTodos() {
      // Get our rows.
      var rowsToRemove = document.querySelectorAll('input[name=select-row]:checked');
    
      for (var i = 0; i < rowsToRemove.length; i++) {
        // Delete the row.
        removeTodo(rowsToRemove[i].value);
      }
    }
    <table>
      <thead>
        <tr>
          <!-- 8 ) Add a 'select all' checkbox. -->
          <th><input onchange="toggleSelection(this);" type='checkbox'></th>
          <th>Index</th>
          <th>Part</th>
          <th>Pieces</th>
          <th>Weight</th>
          <!-- 9 ) Add a 'delete selected' button -->
          <th><button onclick='removeSelectedTodos();'>x</button></th>
        </tr>
      </thead>
      <tbody id="todoList">
      </tbody>
    </table>
    
    <form>
      <fieldset>
        <div class="tableContainer">
          <label for="index">
            <select id="index" name="index"> 
              <option hidden="" >Index</option> 
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
            </select>
          </label>
          <input placeholder="part" id="part" />
          <input placeholder="pieces" id="pieces" />
          <input placeholder="weight" id="weight" />
          <input type="button" id="submit" value="ADD" onclick="addTodosToPage()">
        </div>
      </fieldset>
    </form>

    As for updating the todo list on the server: your current code is already on track to do that. If you submit the values to the server and it saves them into a json file that overwrites the old one, you've updated the server's version of the todo list.

    Hope this helps!

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入