如何将Post请求中的jQuery替换为原生JavaScript?
Got it! Let's walk through how to replace your jQuery POST request with vanilla JavaScript. I’ll cover two practical approaches: the modern Fetch API (the go-to for most modern projects) and the older XMLHttpRequest (if you need to support legacy browsers like IE).
First, let’s assume your original jQuery POST looks something like this (a super common pattern):
$.post('/api/submit-form', { username: 'surajthemighty', message: 'Replacing jQuery with vanilla JS!' }, function(response) { console.log('Request succeeded:', response); }) .fail(function(error) { console.error('Request failed:', error); });
Using the Fetch API (Modern Approach)
The Fetch API is promise-based, clean, and supported by all modern browsers. It’s the recommended replacement for jQuery’s AJAX methods. Here’s how to convert the above code:
Option 1: Using .then() syntax
fetch('/api/submit-form', { method: 'POST', // Match jQuery's default Content-Type for form data headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, // Encode data the same way jQuery does for form-urlencoded requests body: new URLSearchParams({ username: 'surajthemighty', message: 'Replacing jQuery with vanilla JS!' }) }) .then(response => { // Fetch doesn't auto-reject on HTTP errors (like 404/500) if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } // Parse JSON response (mimics jQuery's automatic JSON parsing) return response.json(); }) .then(data => { console.log('Request succeeded:', data); }) .catch(error => { console.error('Request failed:', error); });
Option 2: Using async/await (cleaner for sequential code)
If you prefer more readable, synchronous-looking code, use async/await:
async function submitForm() { try { const response = await fetch('/api/submit-form', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: new URLSearchParams({ username: 'surajthemighty', message: 'Replacing jQuery with vanilla JS!' }) }); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const data = await response.json(); console.log('Request succeeded:', data); } catch (error) { console.error('Request failed:', error); } } // Call the function to trigger the request submitForm();
Key Equivalents to jQuery:
method: 'POST'replaces jQuery’s implicit POST method in$.postheaderslets you set the same request headers jQuery auto-injects (likeContent-Type)bodyholds your request data (useURLSearchParamsfor form-encoded data, orJSON.stringify()if sending JSON)response.json()mimics jQuery’s automatic JSON parsing- The
if (!response.ok)check handles HTTP errors that would trigger jQuery’s.fail()callback
Using XMLHttpRequest (Legacy Browser Support)
If you need to support older browsers like Internet Explorer, use XMLHttpRequest—this is actually what jQuery uses under the hood for AJAX requests:
// Create a new XHR object const xhr = new XMLHttpRequest(); // Initialize the POST request (third param = async, matches jQuery's default) xhr.open('POST', '/api/submit-form', true); // Set the Content-Type header to match jQuery's default xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Handle successful responses xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { // Parse the JSON response const response = JSON.parse(xhr.responseText); console.log('Request succeeded:', response); } else { // Handle HTTP errors console.error('Request failed:', xhr.statusText); } }; // Handle network-level errors xhr.onerror = function() { console.error('Network error occurred'); }; // Send the encoded data xhr.send(new URLSearchParams({ username: 'surajthemighty', message: 'Replacing jQuery with vanilla JS!' }).toString());
Key Notes to Keep in Mind
- Sending JSON? If your original jQuery request sends JSON instead of form data, update the
headersto'Content-Type': 'application/json'and setbodytoJSON.stringify(yourData). - Cookies for authenticated requests? Add
credentials: 'same-origin'(or'include'for cross-origin) to the fetch options object to send cookies, just like jQuery does by default. - Working with HTML forms? You can create a
FormDataobject directly from the form element (new FormData(document.getElementById('your-form'))) and pass it as thebody—no need to setContent-Type, the browser handles it automatically.
内容的提问来源于stack exchange,提问作者surajthemighty

