Làm cách nào để gửi dữ liệu từ HTML sang JSON?

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', 'https://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ậy

Mộ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', 'https://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', 'https://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', 'https://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', 'https://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' });
})
2

Ghi 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
    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', 'https://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 theo cách thủ công
  • Sử dụng 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', 'https://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 lập
  • 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', 'https://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 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', 'https://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

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', 'https://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', 'https://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ẫu

Hãy xem một ví dụ

<button>Click Me!button>

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', 'https://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', 'https://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à HTTP

Sử 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', 'https://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', 'https://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ệu

Sử 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

<button>Click Me!button>

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', 'https://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', 'https://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', 'https://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', 'https://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ẫu

HTML 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', 'https://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

Như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', 'https://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

<button>Click Me!button>
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', 'https://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
<button>Click Me!button>
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àm

Có nhiều nguồn dữ liệu nhị phân, bao gồm

<button>Click Me!button>
8,
<button>Click Me!button>
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
<button>Click Me!button>
8, hãy xem Sử dụng tệp từ ứng dụng web

Cá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', 'https://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', 'https://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ơn

Trong ví dụ sau, chúng tôi sử dụng API

<button>Click Me!button>
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 tay

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', 'https://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

Như 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', 'https://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 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', 'https://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', 'https://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ũ

Làm cách nào để lấy JSON từ biểu mẫu HTML?

Sau đây là các bước. .
Tạo biểu mẫu với đầu vào của nó và gửi đầu vào/nút như bạn thường làm
Cung cấp cho biểu mẫu một Id duy nhất
Thêm trình xử lý sự kiện gửi vào biểu mẫu và chuyển đối tượng sự kiện cùng với nó
Xây dựng phần thân yêu cầu ở định dạng JSON bằng lớp FormData
Thêm bất kỳ tiêu đề nào, nếu cần

Làm cách nào để gửi dữ liệu đến tệp JSON?

Gửi dữ liệu JSON từ phía máy khách . Use JSON. stringify() để chuyển đổi đối tượng JavaScript thành chuỗi JSON. Gửi chuỗi JSON được mã hóa URL tới máy chủ như một phần của Yêu cầu HTTP. Điều này có thể được thực hiện bằng phương thức HEAD, GET hoặc POST bằng cách gán chuỗi JSON cho một biến.

HTML có được gửi dưới dạng JSON không?

HTML không cung cấp cách tạo JSON từ dữ liệu biểu mẫu . Nếu bạn thực sự muốn xử lý nó từ máy khách, thì bạn sẽ phải sử dụng JavaScript để. thu thập dữ liệu của bạn từ biểu mẫu qua DOM.

Làm cách nào để chuyển đổi phản hồi HTML thành JSON trong Java?

Các bước chuyển đổi HTML sang JSON qua Java .
Tải tệp HTML với một phiên bản của lớp Workbook
Sổ làm việc cuộc gọi. phương pháp lưu
Truyền đường dẫn đầu ra với phần mở rộng JSON làm tham số
Kiểm tra đường dẫn được chỉ định cho tệp JSON kết quả