Biểu mẫu HTML có thể gửi yêu cầu HTTP theo cách khai báo. Nhưng các biểu mẫu cũng có thể chuẩn bị một yêu cầu HTTP để gửi qua JavaScript, chẳng hạn như qua
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
9. Bài viết này khám phá những cách tiếp cận như vậyMột hình thức không phải lúc nào cũng là một hình thức
Với các ứng dụng web lũy tiến, ứng dụng trang đơn và ứng dụng dựa trên khung, người ta thường sử dụng biểu mẫu HTML để gửi dữ liệu mà không cần tải tài liệu mới khi nhận được dữ liệu phản hồi. Trước tiên hãy nói về lý do tại sao điều này đòi hỏi một cách tiếp cận khác
Giành quyền kiểm soát giao diện toàn cầu
Gửi biểu mẫu HTML tiêu chuẩn, như được mô tả trong bài viết trước, tải URL nơi dữ liệu được gửi, có nghĩa là cửa sổ trình duyệt điều hướng khi tải toàn bộ trang. Tránh tải toàn bộ trang có thể mang lại trải nghiệm mượt mà hơn bằng cách tránh giật mạng và các sự cố hình ảnh có thể xảy ra như nhấp nháy
Nhiều giao diện người dùng hiện đại chỉ sử dụng các biểu mẫu HTML để thu thập thông tin đầu vào từ người dùng chứ không phải để gửi dữ liệu. Khi người dùng cố gắng gửi dữ liệu, ứng dụng sẽ kiểm soát và truyền dữ liệu không đồng bộ trong nền, chỉ cập nhật những phần của giao diện người dùng yêu cầu thay đổi
Gửi dữ liệu tùy ý không đồng bộ thường được gọi là AJAX, viết tắt của "JavaScript và XML không đồng bộ"
Nó khác nhau như thế nào?
Đối tượng DOM
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
9 [XHR] có thể xây dựng các yêu cầu HTTP, gửi chúng và truy xuất kết quả của chúng. Trước đây, const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
9 được thiết kế để tìm nạp và gửi XML dưới dạng định dạng trao đổi, định dạng này đã được thay thế bởi JSON. Nhưng cả XML và JSON đều không phù hợp với mã hóa yêu cầu dữ liệu biểu mẫu. Dữ liệu biểu mẫu [const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
1] được tạo từ danh sách các cặp khóa/giá trị được mã hóa URL. Để truyền dữ liệu nhị phân, yêu cầu HTTP được định hình lại thành const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
2Ghi chú. Ngày nay, API tìm nạp thường được sử dụng thay cho XHR — đây là phiên bản cập nhật, hiện đại của XHR, hoạt động tương tự nhưng có một số ưu điểm. Hầu hết mã XHR mà bạn sẽ thấy trong bài viết này có thể được hoán đổi cho Tìm nạp
Nếu bạn kiểm soát giao diện người dùng [mã được thực thi trong trình duyệt] và back-end [mã được thực thi trên máy chủ], bạn có thể gửi JSON/XML và xử lý chúng theo cách bạn muốn
Nhưng nếu bạn muốn sử dụng dịch vụ của bên thứ ba, bạn cần gửi dữ liệu theo định dạng mà dịch vụ yêu cầu
Vì vậy, làm thế nào chúng ta nên gửi dữ liệu như vậy?
Gửi dữ liệu biểu mẫu
Có 3 cách để gửi dữ liệu biểu mẫu
- Xây dựng một
9 theo cách thủ côngconst btn = document.querySelector['button']; function sendData[data] { console.log['Sending data']; const XHR = new XMLHttpRequest[]; const urlEncodedDataPairs = []; // Turn the data object into an array of URL-encoded key/value pairs. for [const [name, value] of Object.entries[data]] { urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`]; } // Combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behavior of browser form submissions. const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+']; // Define what happens on successful data submission XHR.addEventListener['load', [event] => { alert['Yeah! Data sent and response loaded.']; }]; // Define what happens in case of an error XHR.addEventListener['error', [event] => { alert['Oops! Something went wrong.']; }]; // Set up our request XHR.open['POST', '//example.com/cors.php']; // Add the required HTTP header for form data POST requests XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded']; // Finally, send our data. XHR.send[urlEncodedData]; } btn.addEventListener['click', [] => { sendData[{ test: 'ok' }]; }]
- Sử dụng một đối tượng
4 độc lậpconst btn = document.querySelector['button']; function sendData[data] { console.log['Sending data']; const XHR = new XMLHttpRequest[]; const urlEncodedDataPairs = []; // Turn the data object into an array of URL-encoded key/value pairs. for [const [name, value] of Object.entries[data]] { urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`]; } // Combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behavior of browser form submissions. const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+']; // Define what happens on successful data submission XHR.addEventListener['load', [event] => { alert['Yeah! Data sent and response loaded.']; }]; // Define what happens in case of an error XHR.addEventListener['error', [event] => { alert['Oops! Something went wrong.']; }]; // Set up our request XHR.open['POST', '//example.com/cors.php']; // Add the required HTTP header for form data POST requests XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded']; // Finally, send our data. XHR.send[urlEncodedData]; } btn.addEventListener['click', [] => { sendData[{ test: 'ok' }]; }]
- Sử dụng
4 liên kết với phần tửconst btn = document.querySelector['button']; function sendData[data] { console.log['Sending data']; const XHR = new XMLHttpRequest[]; const urlEncodedDataPairs = []; // Turn the data object into an array of URL-encoded key/value pairs. for [const [name, value] of Object.entries[data]] { urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`]; } // Combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behavior of browser form submissions. const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+']; // Define what happens on successful data submission XHR.addEventListener['load', [event] => { alert['Yeah! Data sent and response loaded.']; }]; // Define what happens in case of an error XHR.addEventListener['error', [event] => { alert['Oops! Something went wrong.']; }]; // Set up our request XHR.open['POST', '//example.com/cors.php']; // Add the required HTTP header for form data POST requests XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded']; // Finally, send our data. XHR.send[urlEncodedData]; } btn.addEventListener['click', [] => { sendData[{ test: 'ok' }]; }]
6const btn = document.querySelector['button']; function sendData[data] { console.log['Sending data']; const XHR = new XMLHttpRequest[]; const urlEncodedDataPairs = []; // Turn the data object into an array of URL-encoded key/value pairs. for [const [name, value] of Object.entries[data]] { urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`]; } // Combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behavior of browser form submissions. const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+']; // Define what happens on successful data submission XHR.addEventListener['load', [event] => { alert['Yeah! Data sent and response loaded.']; }]; // Define what happens in case of an error XHR.addEventListener['error', [event] => { alert['Oops! Something went wrong.']; }]; // Set up our request XHR.open['POST', '//example.com/cors.php']; // Add the required HTTP header for form data POST requests XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded']; // Finally, send our data. XHR.send[urlEncodedData]; } btn.addEventListener['click', [] => { sendData[{ test: 'ok' }]; }]
Hãy xem xét chúng một cách chi tiết
Xây dựng XMLHttpRequest theo cách thủ công
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
9 là cách an toàn và đáng tin cậy nhất để thực hiện các yêu cầu HTTP. Để gửi dữ liệu biểu mẫu với const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
9, hãy chuẩn bị dữ liệu bằng cách mã hóa URL và tuân theo các chi tiết cụ thể của yêu cầu dữ liệu biểu mẫuHãy xem một ví dụ
Click Me!
Và bây giờ là JavaScript
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
Đây là kết quả trực tiếp
Ghi chú. Việc sử dụng
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
9 này tuân theo chính sách cùng nguồn gốc nếu bạn muốn gửi dữ liệu đến trang web của bên thứ ba. Đối với các yêu cầu nguồn gốc chéo, bạn sẽ cần kiểm soát truy cập CORS và HTTPSử dụng XMLHttpRequest và đối tượng FormData
Xây dựng một yêu cầu HTTP bằng tay có thể quá sức. May mắn thay, đặc tả XMLHttpRequest cung cấp một cách mới hơn, đơn giản hơn để xử lý các yêu cầu dữ liệu biểu mẫu với đối tượng
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
4Đối tượng
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
4 có thể được sử dụng để tạo dữ liệu biểu mẫu để truyền hoặc để lấy dữ liệu trong thành phần biểu mẫu để quản lý cách gửi dữ liệuSử dụng đối tượng này được trình bày chi tiết trong Sử dụng Đối tượng FormData, nhưng đây là hai ví dụ
Sử dụng đối tượng FormData độc lập
Click Me!
Bạn nên làm quen với mẫu HTML đó. Bây giờ cho JavaScript
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
0Đây là kết quả trực tiếp
Sử dụng FormData được liên kết với một phần tử biểu mẫu
Bạn cũng có thể liên kết một đối tượng
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
4 với một phần tử const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
6. Điều này tạo ra một đối tượng const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
4 đại diện cho dữ liệu có trong biểu mẫuHTML là điển hình
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
4Nhưng JavaScript chiếm lấy hình thức
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
5Đây là kết quả trực tiếp
Bạn thậm chí có thể tham gia nhiều hơn vào quy trình bằng cách sử dụng thuộc tính
Click Me!
5 của biểu mẫu để nhận danh sách tất cả các thành phần dữ liệu trong biểu mẫu và quản lý từng thành phần dữ liệu theo cách thủ công. Để tìm hiểu thêm về điều đó, hãy xem ví dụ trong Truy cập nội dung của danh sách phần tử trong HTMLFormElement. yếu tốXử lý dữ liệu nhị phân
Nếu bạn sử dụng đối tượng
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
4 với biểu mẫu bao gồm tiện ích con Click Me!
7, dữ liệu sẽ được xử lý tự động. Nhưng để gửi dữ liệu nhị phân bằng tay, còn nhiều việc phải làmCó nhiều nguồn dữ liệu nhị phân, bao gồm
Click Me!
8, Click Me!
9 và WebRTC. Thật không may, một số trình duyệt cũ không thể truy cập dữ liệu nhị phân hoặc yêu cầu cách giải quyết phức tạp. Để tìm hiểu thêm về API Click Me!
8, hãy xem Sử dụng tệp từ ứng dụng webCách ít phức tạp nhất để gửi dữ liệu nhị phân là sử dụng phương pháp
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
02 của const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
4, được trình bày ở trên. Nếu phải làm thủ công thì phức tạp hơnTrong ví dụ sau, chúng tôi sử dụng API
Click Me!
8 để truy cập dữ liệu nhị phân và sau đó tạo yêu cầu dữ liệu biểu mẫu nhiều phần bằng tayconst btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
5Như bạn thấy, HTML là một
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
6 tiêu chuẩn. Không có gì kỳ diệu xảy ra. "Ma thuật" là trong JavaScriptconst btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
7Đây là kết quả trực tiếp
Phần kết luận
Tùy thuộc vào trình duyệt và loại dữ liệu bạn đang xử lý, việc gửi dữ liệu biểu mẫu qua JavaScript có thể dễ dàng hoặc khó khăn. Đối tượng
const btn = document.querySelector['button'];
function sendData[data] {
console.log['Sending data'];
const XHR = new XMLHttpRequest[];
const urlEncodedDataPairs = [];
// Turn the data object into an array of URL-encoded key/value pairs.
for [const [name, value] of Object.entries[data]] {
urlEncodedDataPairs.push[`${encodeURIComponent[name]}=${encodeURIComponent[value]}`];
}
// Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behavior of browser form submissions.
const urlEncodedData = urlEncodedDataPairs.join['&'].replace[/%20/g, '+'];
// Define what happens on successful data submission
XHR.addEventListener['load', [event] => {
alert['Yeah! Data sent and response loaded.'];
}];
// Define what happens in case of an error
XHR.addEventListener['error', [event] => {
alert['Oops! Something went wrong.'];
}];
// Set up our request
XHR.open['POST', '//example.com/cors.php'];
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader['Content-Type', 'application/x-www-form-urlencoded'];
// Finally, send our data.
XHR.send[urlEncodedData];
}
btn.addEventListener['click', [] => {
sendData[{ test: 'ok' }];
}]
4 nói chung là câu trả lời và bạn có thể sử dụng một polyfill cho nó trên các trình duyệt cũ