Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách tạo jQuery post() Request

Khi xây dựng web app, chắc chắn sẽ phải tạo cái gì từ dữ liệu user nhập. Có thể tạo tài khoản mới khi submit thông tin qua form đăng ký, hoặc tạo công thức mới từ app quản lý công thức tuyệt vời. Từ dữ liệu user trong form đến instance recipe mới lưu database cần HTTP POST request.

POST request gửi dữ liệu từ form đến server nơi tạo trong backend/API và lưu database. Mặc định, submit form yêu cầu redirect hoặc page refresh. Dù ổn cho app nhỏ, muốn trải nghiệm load nhanh hơn nên override behavior này.

Dùng jQuery post() request cho phép làm HTTP request, nhận response, chọn cách hiển thị dữ liệu KHIÔNG redirect/refresh! Xem kỹ post() cần gì để làm tất cả này.

Nhìn gần vào post()

HTTP requests như trò chơi ném bắt. Browser ném request đến server qua API endpoint, server ném lại response. post() gửi data đến endpoint sẽ được tạo và lưu database app.

Xét trên, post() nhận arguments, đúng không? Đúng! post() nhận tới 4 arguments, nhưng cho mục đích ta, focus 2 chính: URL destination và data gửi đến destination.

$.post('/recipes', data)

Với ví dụ app tổ chức công thức, bắt đầu với jQuery selector $. Gọi post() method, gửi data đến URL '/recipes'. Đến đây ổn. Đã ném data đến server. Giờ chuẩn bị catch response!

Response trả về là jQuery XHR object, hoặc jqXHR, implement Promise interface. Đừng lo! Câu đó nghe scary nhưng nói response chỉ là object. Với done() method tiện lợi của jQuery, object đó tổ chức thành format dễ đọc hơn.

Giữ analogy ném bắt: ném data đến server với post(). Ném lại jqXHR object, pass cho done() để xem bắt được gì. Đã xem kỹ post(), xem cách dùng.

jQuery post()

Bắt đầu với plain HTML form:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 
<h2> New Recipe </h2> 
<form id='new-recipe'> 
  <label for="name">Recipe Name</label><br> 
  <input type="text" name="name" id="name"><br> 
  <label for="ingredients">Ingredients</label><br> 
  <input type="text" name="ingredients" id="ingredients"><br> 
  <button type="submit"> Create Recipe </button> 
</form>

Hiển thị form như:

Cách tạo jQuery post() Request

Mặc định, click submit button, browser refresh/redirect. Nhớ muốn tránh refresh/redirect? Nếu refresh/redirect, mất data form. Để tránh redirect mất data, dùng JS preventDefault() method.

<script> 
$(document).ready(() => { 
  $('#new-recipe').submit((event) => { 
    event.preventDefault(); 
  }) 
}) 
</script>

Đợi page/document load, lắng nghe click submit trên form id new-recipe. Thực hiện với .submit() method nhận callback function với click event làm argument. Nhắc lại, JS callback function là function pass as argument cho function khác execute sau.

Từ trong callback, ngăn default redirect với preventDefault(). Giờ không redirect, bắt đầu submit data đến server.

Trước khi invoke post() gửi data, cần data! Lấy data đâu?

Lấy từ form. Vì không redirect, có access giá trị text inputs form. serialize() method làm gì?

serialize() gọi trên form chọn với từ khóa this. serialize() chuyển form data thành text string standard URL-encoded notation, gửi được server.

Sau khi serialize đúng, lưu vào biến:

$(document).ready(() => { 
  $('#new-recipe').submit((event) => { 
    event.preventDefault(); 
    var values = $(this).serialize(); 
  }) 
})

Giờ data lưu trong biến values, gửi đi server!

$(document).ready(() => { 
  $('#new-recipe').submit((event) => { 
    event.preventDefault(); 
    var values = $(this).serialize(); 
    var posting = $.post('/recipes', values); 
  }) 
})

Nhớ post() trả về jqXHR object? Lưu làm biến và gọi done() lên nó unpack response xử lý client-side.

$(document).ready(() => { 
  $('#new-recipe').submit((e) => { 
    e.preventDefault(); 
    var values = $(this).serialize(); 
    var posting = $.post('/recipes', values); 
    posting.done( (data) => { 
      var recipe = data; 
      $('.recipes').text(recipe["name"]); 
      $('.recipes').text(recipe["ingredients"]); 
    }) 
  }) 
})

Sau nhận data lưu biến readable recipe, truy cập attribute name và ingredient. Ví dụ, chèn attribute vào <div> class recipes.

Cách tạo jQuery post() Request

Kết luận

Đã bao quát nhiều! Trước khi celebrate học post(), tóm tắt nhanh:

Use case phổ biến post() là trong .submit() làm callback function. Vì .submit() gọi trên form, dùng JS this keyword tham chiếu tất cả data form và serialize() nó. Sau khi lưu serialized data vào biến (thường gọi values), gửi values đến destination URL dùng post().

Thói quen tốt lưu jqXHR object trả về post() vào biến thường gọi posting. Từ đây dùng done() method tiện lợi trên posting variable, giờ có access data server response. Tùy bạn hiển thị data cho user.

Chúc mừng mình đã giải quyết quy trình phức tạp post()! Nếu ở giai đoạn build app riêng, nhớ errors happen. Stay calm and debug!