iT邦幫忙

0

ajax post 執行跟 put 一樣 (is processing, but like put......) ,怎麼改

  • 分享至 

  • xImage

我的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"

https://ithelp.ithome.com.tw/upload/images/20230621/20160976SE9UWKSgHW.png

我目前是能想到

  • 我輸入的新數據有被整合,封包
  • 有確實給到伺服器(她都拿去比對了)
  • 但她以為是 put 而非 post

所以需要怎麼改?


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

看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2023-06-21 09:41:10 檢舉
這應該不是http method的問題,你用什麼http method去打,你可以在開發者模式下的網路那邊找到。
這個訊息看起來是你給的device_id不對。
要看後端程式碼才能確定,前端粗略看過應該沒問題。
我是新增新的 data, device_id 應該可以隨便寫才對。我有把 新的input 封包成"send_Edit_API_Data ",再寄給server。

- 從website 到 server 會失敗( 如本問題的post 變 put)
- 從fastAPI 介面就送一樣格式的資料就可以成功
froce iT邦大師 1 級 ‧ 2023-06-21 10:33:00 檢舉
你懷疑post變put你就去後端print一下接進來的request,和瀏覽器開發者模式裡網路打出來的封包比對一下就行,解決方法都告訴你了。
好,那我試試看
不好意思,我太菜了,還是不會,可以多講一下嗎?感恩
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答