如何将基于Fetch API的表单提交代码转换为jQuery Ajax实现
Let's break this down in a way that fits your familiar jQuery workflow. First, let's map what the original Fetch API code was doing: it binds to the submit button click, stops the default form submission, then makes a request to page.cfm and starts accessing response details like content length.
Here's how to adapt that logic to match your existing jQuery Ajax style, while keeping all your preferred settings intact:
Updated jQuery Ajax Implementation
$(":submit").click(function(event) { // Stop the default form submission behavior, same as Fetch's event.preventDefault() event.preventDefault(); $.ajax({ url: "page.cfm", cache: false, data: $('#form').serialize(), // Keep your existing form data serialization method: "post", beforeSend: function() { $('div.results').html('Please wait'); }, success: function(response, textStatus, jqXHR) { // Update results with the response, just like your original code $('div.results').html(response); // Replicate the Fetch code's Content-Length header check const contentLength = jqXHR.getResponseHeader("Content-Length") * 1; console.log("Response content length:", contentLength); }, error: function(jqXHR, textStatus, errorThrown) { // Optional but useful: add error handling for robustness $('div.results').html("Oops, something went wrong: " + errorThrown); } }); });
Key Details to Note:
- We added the
$(":submit").click()handler to match the original Fetch code's event binding, plusevent.preventDefault()to block the default form submit action. - All your original jQuery Ajax settings (cache control, serialized form data, POST method, loading state) are preserved—no need to change what you're already comfortable with.
- To replicate the
response.headers.get("Content-Length")line from Fetch, we usejqXHR.getResponseHeader("Content-Length")in the success callback. jQuery's jqXHR object gives you access to response headers just like Fetch's response object does. - The optional error handler is a small addition to make the code more resilient, which is good practice even if the original Fetch snippet didn't include it.
One quick caveat: if the original Fetch code was planning to use the response.body.getReader() for streaming responses, jQuery Ajax doesn't support streaming natively (it's built on XMLHttpRequest, which lacks Fetch's ReadableStream capabilities). But if streaming isn't a requirement for your use case, the code above covers all the core functionality from the Fetch snippet.
内容的提问来源于stack exchange,提问作者Regual

