AJAX gửi biểu mẫu JavaScript

AJAX (JavaScript và XML không đồng bộ) là nghệ thuật trao đổi dữ liệu với máy chủ và cập nhật các phần của trang web – mà không cần tải lại toàn bộ trang

Bài đăng trên blog trước đây của chúng tôi đã giải thích về việc gửi biểu mẫu mà không cần làm mới trang, nhưng nó đã được thực hiện bằng cách sử dụng  ajax, PHP và jQuery

Bây giờ bạn sẽ tìm hiểu chức năng tương tự bằng cách sử dụng ajax, PHP và Javascript thông qua bài đăng trên blog này. Chỉ cần theo dõi bài viết của chúng tôi hoặc tải xuống để sử dụng


AJAX gửi biểu mẫu JavaScript


Đối với điều này, bạn phải có một cơ sở dữ liệu trong MYSQL. Ở đây, chúng ta có cơ sở dữ liệu tên là “mydba” bao gồm bảng tên là “form_element” với 5 trường

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 XMLHttpRequest. Bài viết này khám phá những cách tiếp cận như vậy

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

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ộ"

Đối tượng DOM XMLHttpRequest (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, XMLHttpRequest đượ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?

Có 3 cách để gửi dữ liệu biểu mẫu

  • Xây dựng một XMLHttpRequest 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

XMLHttpRequest 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 XMLHttpRequest, 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 XMLHttpRequest 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

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 phần tử 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 một đố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) {
  const XHR = new XMLHttpRequest();
  const FD = new FormData();

  // Push our data into our FormData object
  for (const [name, value] of Object.entries(data)) {
    FD.append(name, value);
  }

  // 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');

  // Send our FormData object; HTTP headers are set automatically
  XHR.send(FD);
}

btn.addEventListener('click', () => {
  sendData({ test: 'ok' });
});

Đâ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

<form id="myForm">
  <label for="myName">Send me your name:label>
  <input id="myName" name="name" value="Dominic" />
  <input type="submit" value="Send Me!" />
form>

Nhưng JavaScript chiếm lấy hình thức

window.addEventListener("load", () => {
  function sendData() {
    const XHR = new XMLHttpRequest();

    // Bind the FormData object and the form element
    const FD = new FormData(form);

    // Define what happens on successful data submission
    XHR.addEventListener("load", (event) => {
      alert(event.target.responseText);
    });

    // Define what happens in case of error
    XHR.addEventListener("error", (event) => {
      alert('Oops! Something went wrong.');
    });

    // Set up our request
    XHR.open("POST", "https://example.com/cors.php");

    // The data sent is what the user provided in the form
    XHR.send(FD);
  }

  // Get the form element
  const form = document.getElementById("myForm");

  // Add 'submit' event handler
  form.addEventListener("submit", (event) => {
    event.preventDefault();

    sendData();
  });
});

Đâ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ụ

Nếu bạn 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 với biểu mẫu bao gồm các 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ừ các ứ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) {
  const XHR = new XMLHttpRequest();
  const FD = new FormData();

  // Push our data into our FormData object
  for (const [name, value] of Object.entries(data)) {
    FD.append(name, value);
  }

  // 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');

  // Send our FormData object; HTTP headers are set automatically
  XHR.send(FD);
}

btn.addEventListener('click', () => {
  sendData({ test: 'ok' });
});
2 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 đó xây dựng yêu cầu dữ liệu biểu mẫu nhiều phần bằng tay

<form id="theForm">
  <p>
    <label for="theText">text data:label>
    <input id="theText" name="myText" value="Some text data" type="text" />
  p>
  <p>
    <label for="theFile">file data:label>
    <input id="theFile" name="myFile" type="file" />
  p>
  <button>Send Me!button>
form>

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

// Because we want to access DOM nodes,
// we initialize our script at page load.
window.addEventListener('load', () => {

  // These variables are used to store the form data
  const text = document.getElementById("theText");
  const file = {
    dom: document.getElementById("theFile"),
    binary: null,
  };

  // Use the FileReader API to access file content
  const reader = new FileReader();

  // Because FileReader is asynchronous, store its
  // result when it finishes reading the file
  reader.addEventListener("load", () => {
    file.binary = reader.result;
  });

  // At page load, if a file is already selected, read it.
  if (file.dom.files[0]) {
    reader.readAsBinaryString(file.dom.files[0]);
  }

  // If not, read the file once the user selects it.
  file.dom.addEventListener("change", () => {
    if (reader.readyState === FileReader.LOADING) {
      reader.abort();
    }

    reader.readAsBinaryString(file.dom.files[0]);
  });

  // sendData is our main function
  function sendData() {
    // If there is a selected file, wait until it is read
    // If there is not, delay the execution of the function
    if (!file.binary && file.dom.files.length > 0) {
      setTimeout(sendData, 10);
      return;
    }

    // To construct our multipart form data request,
    // We need an XMLHttpRequest instance
    const XHR = new XMLHttpRequest();

    // We need a separator to define each part of the request
    const boundary = "blob";

    // Store our body request in a string.
    let data = "";

    // So, if the user has selected a file
    if (file.dom.files[0]) {
      // Start a new part in our body's request
      data += `--${boundary}\r\n`;

      // Describe it as form data
      data += 'content-disposition: form-data; '
      // Define the name of the form data
            + `name="${file.dom.name}"; `
      // Provide the real name of the file
            + `filename="${file.dom.files[0].name}"\r\n`;
      // And the MIME type of the file
      data += `Content-Type: ${file.dom.files[0].type}\r\n`;

      // There's a blank line between the metadata and the data
      data += '\r\n';

      // Append the binary data to our body's request
      data += file.binary + '\r\n';
    }

    // Text data is simpler
    // Start a new part in our body's request
    data += `--${boundary}\r\n`;

    // Say it's form data, and name it
    data += `content-disposition: form-data; name="${text.name}"\r\n`;
    // There's a blank line between the metadata and the data
    data += '\r\n';

    // Append the text data to our body's request
    data += text.value + "\r\n";

    // Once we are done, "close" the body's request
    data += `--${boundary}--`;

    // 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 to handle a multipart form data POST request
    XHR.setRequestHeader('Content-Type', `multipart/form-data; boundary=${boundary}`);

    // Send the data
    XHR.send(data);
  }

  // Get the form element
  const form = document.getElementById('theForm');

  // Add 'submit' event handler
  form.addEventListener('submit', (event) => {
    event.preventDefault();
    sendData();
  });
});

Đây là kết quả trực tiếp

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 để gửi biểu mẫu AJAX trong JavaScript?

Để gửi biểu mẫu qua AJAX, tập lệnh của bạn sẽ cần xử lý bốn tác vụ. .
Chụp nút gửi biểu mẫu để hành động mặc định không diễn ra
Nhận tất cả dữ liệu từ biểu mẫu bằng jQuery
Gửi dữ liệu biểu mẫu bằng AJAX
Hiển thị lỗi nếu có

Làm cách nào để gửi biểu mẫu thông qua JavaScript?

Khi chúng ta click vào link thì hàm submitForm() sẽ được thực thi. Hàm này sẽ lấy đối tượng phần tử bằng phương thức DOM getElementById() bằng cách chuyển id biểu mẫu cho phương thức này, sau đó biểu mẫu sẽ được gửi bằng cách sử dụng phương thức submit(). Thí dụ. Tạo một biểu mẫu và gửi nó bằng cách sử dụng phương pháp trên

Làm cách nào để gửi dữ liệu tệp và biểu mẫu bằng AJAX?

Làm theo ba bước đơn giản sau. .
Tạo biểu mẫu HTML. .
mục lục. html. .
Thêm thư viện JavaScript trên nền tảng đám mây. .
Biểu mẫu HTML Trong thư mục gốc của bạn, hãy tạo một biểu mẫu HTML (một chỉ mục. html) bằng mã sau, chứa các trường để tải tệp lên. .
Lưu ý những điều dưới đây. .
Tập lệnh hỗ trợ AJAX trong JavaScript. .
tập lệnh PHP

Sự khác biệt giữa AJAX và gửi biểu mẫu là gì?

Gửi biểu mẫu tiêu chuẩn sẽ gửi một yêu cầu HTTP mới (POST hoặc GET) và tải trang mới trong trình duyệt. Trong Ajax, dữ liệu được gửi đến máy chủ (POST hoặc GET) ở chế độ nền mà hoàn toàn không ảnh hưởng đến trang và phản hồi sau đó được javascript nhận ở chế độ nền, một lần nữa mà không ảnh hưởng đến trang