我是javascript新手,需要帮助。在代码中,我需要添加两个删除按钮:
此按钮需要删除json文件中的对象。我不知道该如何编写函数,请帮忙! 该代码是用html,javascript和php创建的,并由ajax发送。 对象也必须在网站中删除。
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);
?>
答案 0 :(得分:0)
在我开始之前,我会有点偏执切线,并强调您正在使用的服务器端PHP代码并不安全。对于 PHP magic quotes are deprecated and should be avoided 和第二种情况,准备数据客户端,然后毫无疑问地将其保存到服务器是一个非常不好的主意。
永远不要信任客户端来格式化数据,否则我可以进行以下操作:
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.您仍然可以在客户端上构建JSON文件并将其提交到服务器,但是服务器需要确保正在检查输入是否符合预期。
例如:
<?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 );
我正在消毒所提交的数据,并删除不必要的代码,同时验证所提交数据的格式化方式符合我的期望。
再往前走,我可以使用index
或weight
验证FILTER_VALIDATE_INT
和is_numeric
是数值,然后向用户抱怨。或者我可以用FILTER_SANITIZE_INT
或intval
清除这些值,以确保这些值符合我期望的格式。
但是足够多的安全困扰...我现在会真正回答您的问题。
在不对当前代码进行太多更改的情况下,可以使用复选框列来添加删除按钮或多个删除按钮的一种方法。我在下面的代码中标记了这些更改,但总结一下:
<tr id="row-1"></tr>
removeTodo(1);
removeTodo()
函数。
// 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>
关于更新服务器上的待办事项列表:您当前的代码已经可以执行此操作。如果您将值提交到服务器,并将其保存到覆盖旧文件的json文件中,则说明服务器的待办事项列表版本已更新。
希望这会有所帮助!