代码之家  ›  专栏  ›  技术社区  ›  happy beginer

ajax post按put工作(正在处理,但按put),如何更正

  •  0
  • happy beginer  · 技术社区  · 1 年前

    我的Ajax帖子是按put工作的(用于编辑数据),不过我正在添加新数据,如何更正?

    我已经通读了所有的模板,我确实遵循了模板到达这里,但仍然需要帮助。

    $.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);
      }
    });
    

    我甚至添加了这个(这个头用于指示请求应该被视为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">&times;</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://http://192.168.01.10:8000/api/product/",   /// api change ///
            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>
    

    例如我正在添加新数据 adding new data

    1. 点击“添加新02”按钮
    2. 我填充了新的数据(device_id:'string-new01'等)控制台,所有人都得到了它
    3. 新数据保存为“send_Edit_API_data”
    4. 使用ajax发送到服务器
    5. 刷新时,不会添加新数据

    这个 {detail: 'No IPC with this device_id: string-new01 found'} 我假设是编辑模式,put方法,服务器告诉没有找到这个设备id的IPC:string-new01


    该死,我刚刚发现,“添加”和“编辑”按钮都运行 save() 函数 只有 正在使用 editRow( ) 因此,API将添加作为编辑运行

        function save() {
          // var getData = document.getElementById("#sendData form").val
          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)          
        }
    
    
    0 回复  |  直到 1 年前