我的ajax post 表現跟 put 一樣(put 用來編輯),但我正在添加新數據,如何糾正
我已經閱讀了所有template,並且我確實按照demo 做到8-9成,但仍然需要幫助,謝謝
-這個是主要送過去給伺服器的邏輯
$.ajax({
url : 'http://192.168.01.10:8000/api/product/',
type : 'POST', // post for adding data
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data :JSON.stringify(send_Edit_API_Data) ,
headers: {
'Authorization': 'Bearer ' + getToken // for authorized/safty reason
},
success : function(result) {
console.log("SUCCESS", result)
},
error: function(response){
console.log("ERROR",response);
}
});
我甚至添加了這個(這個tag 用於指示請求應該被視為 POST 請求,即使它作為 PUT 請求發送)但我看伺服器給的反饋,依舊像 put
beforeSend: function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', 'POST');
},
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta tags and other head elements -->
<title>Static Template</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap 4.2.1 CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body>
<div id="app"></div>
<table id="example" class="display"></table>
<!-- JavaScript libraries -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
const getToken = localStorage.getItem("token")
console.log("GET TOKEN", getToken)
var table = $("#example").DataTable({
ajax: {
url: "http://192.168.01.10:3000/api/product",
headers: {
'Authorization': 'Bearer ' + getToken
},
dataSrc: function (response) {
console.log("DATA", response.ipcs);
return response.ipcs
}
},
columns: [
{
data: null,
title: "ACTION",
render: function (data, type, row) {
return '<button type="button" class="btn btn-primary" id="Edit_Data" data-toggle="modal" data-target="#exampleModal" data-whatever=" ">Edit</button>' +
'<button class="btn btn-danger btn-sm delete-btn" id="Delete_Data" data-id="' + row.device_id + '">Delete</button>';
}
},
{ data: "device_id", title: "device_id" },
{ data: "name", title: "name" },
{ data: "group", title: "group" }
]
});
table.draw()
var rowData;
$('#example tbody').on('click', 'button', function (event) {
var data = table.row($(this).parents('tr')).data();
rowData = data;
console.log("GET edit DATA", data)
});
$(function() {
$('#exampleModal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var recipient = button.data('whatever');
var modal = $(this);
var data = rowData;
modal.find('.modal-title').text('Update data ' + recipient);
var inputFields = modal.find('.modal-body input');
if (button.attr('id') == "AddedNew_Data") {
inputFields.val("");
} else {
var keys = Object.keys(data);
for (var i = 0; i < inputFields.length; i++) {
var inputValue = data[keys[i]];
var inputValue = rowData[keys[i]];
$(inputFields[i]).val(inputValue);
}
}
});
});
function editRow_website(id){
var device_id=document.getElementById("device_id"+id);
var name=document.getElementById("name"+id);
var group=document.getElementById("group"+id);
let getEditData = {
"device_id": device_id,
"email_data": name,
"address_data": group,
}
document.getElementById("#editid input").value = device_id
}
$(document).on('click', '.delete-btn', function (event) {
var id = $(this).data('id')
console.log("GET DLETE ID", id)
confirmDelete(id)
});
function deleteData(id) {
$.ajax({
url: "http://192.168.01.10:3000/api/product?device_id="+ id,
type:'DELETE',
headers: {
'Authorization': 'Bearer ' + getToken
},
success: function(response){
console.log(response);
}
}).then(res => console.log("RES", res));
}
function confirmDelete(id) {
if (confirm("sure to delete?")== true) {
var table = $("#example").DataTable();
var row = table.row($(this).closest('tr'));
deleteData(id);
if (row.length > 0) {
row.remove().draw();
console.log("Delete row with id:", id);
}
} else{
none
}
}
});
</script>
<script src="script.js"></script>
<div class ="table-title">
<div class="row">
<div class="col-sm-4">
<!-- <button type="button" class="btn btn-info add-new" onclick="AddRow()"><i class="fa fa-plus"></i>Add New</button> -->
<button type="button" id="AddedNew_Data" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever=" " onclick="AddRow()">Add New02</button>
</div>
</div>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">device_id:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="input_edit_device_id" class="col-form-label">Device ID:</label>
<input type="text" class="form-control" id="input_edit_device_id">
</div>
<div class="form-group">
<label for="input_edit_name" class="col-form-label">name:</label>
<input type="text" class="form-control" id="input_edit_name">
</div>
<!-- Additional form fields -->
<div class="form-group">
<label for="field1" class="col-form-label">group:</label>
<input type="text" class="form-control" id="input_edit_data_group">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="save()">Send message</button>
</div>
</div>
</div>
</div>
<script>
function AddRow() {
const getToken = localStorage.getItem("token")
save();
console.log("Saved Data_added_API_Data:", send_Edit_API_Data);
$("#input_edit_device_id").val("");
$("#input_edit_name").val("");
$("#input_edit_data_group").val("");
}
$.ajax({
url: 'http://192.168.01.10:3000/api/product',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify(send_Edit_API_Data),
headers: {
'Authorization': 'Bearer ' + getToken
},
beforeSend: function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', 'POST');
},
success: function(result) {
console.log("SUCCESS", result);
},
error: function(response) {
console.log("ERROR", response);
}
});
function editRow(data) {
const getToken = localStorage.getItem("token")
console.log("GET TOKEN", getToken)
console.log("EDIT=====", data);
$.ajax({
url: "http:/192.168.01.10:8000/api/product/",
type:'PUT', // aka update or edit
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data :JSON.stringify(data) ,
headers: {
'Authorization': 'Bearer ' + getToken
},
success: function(response){
console.log("SUCCESS",response);
},
error: function(response){
console.log("ERROR",response);
}
})
}
$(function() {
$('#exampleModal').on('show.bs.modal', function(e) {
$('.modalTextInput').val('');
let btn = $(e.relatedTarget); // e.related here is the element that opened the modal, specifically the row button
let id = btn.data('id'); // this is how you get the of any `data` attribute of an element
$('.saveEdit').data('id', id); // then pass it to the button inside the modal
})
$('.saveEdit').on('click', function() {
let id = $(this).data('id'); // the rest is just the same
saveNote(id);
$('#exampleModal').modal('toggle'); // this is to close the modal after clicking the modal button
})
})
function saveNote(id) {
let text = $('.modalTextInput').val();
$('.recentNote').data('note', text);
console.log($('.recentNote').data('note'));
console.log(text + ' --> ' + id);
}
</script>
<script>
var storedItem = localStorage.getItem("storedItem") || [];
function save() {
var itemValue_device_id = document.getElementById("input_edit_device_id").value || "";
var itemValue_edit_name = document.getElementById("input_edit_name").value || "";
var itemValue_data_group = document.getElementById("input_edit_data_group").value || "";
console.log("itemValue_device_id", itemValue_device_id, typeof(itemValue_device_id));
console.log("itemValue_edit_name", itemValue_edit_name, typeof(itemValue_edit_name));
console.log("itemValue_data_group", itemValue_data_group, typeof(itemValue_data_group));
let send_Edit_API_Data = {
device_id:itemValue_device_id,
name:itemValue_edit_name,
group: itemValue_data_group,
}
console.log("send_Edit_API_Data", send_Edit_API_Data);
editRow(send_Edit_API_Data)
}
</script>
</body>
</html>
比如我要添加新data [adding new data][1]
1.我們點擊我網頁上的“Add New02”按鈕
2. 填寫新數據new data (device_id: 'string-new01' and etc) console 也有吃到
3. the new data is saved as "send_Edit_API_Data"
4. 用 ajax send to server
5. 當我refresh的時候, 剛加的 new data 沒有被新增?!
the {detail: 'No IPC with this device_id: string-new01 found'}
我猜想是 edit mode, the put method, 伺服器回傳 "No IPC with this device_id: string-new01 found"
我目前是能想到
所以需要怎麼改?
Damm, I just found out, both "add" and "edit" button run save()
function, in which only use editRow( )
api, therefore, (both inclouding) add is run as edit