JavaScript新手求助:$未定义错误及文件上传后页面不跳转问题
Hey there! Let's tackle those two problems you're facing with your file upload code:
1. Fixing ReferenceError: $ is not defined
The error pops up because your custom script runs before jQuery is loaded. Browsers execute code from top to bottom, so when it hits $(function()...), the jQuery library hasn't been loaded yet—meaning $ doesn't exist in the browser's context.
Quick Fix: Move the jQuery <script> tag above your custom script so it loads first:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script> // Your custom upload code goes here </script>
2. Preventing Page Jump & Showing Response in Alert
By default, submitting a form makes the browser navigate to the action URL. To stay on your current page and display the server response in an alert, you need to:
- Stop the form's default submission behavior
- Use jQuery's
$.ajax()to send the file asynchronously (without page reload)
Note: The upload() method you tried using isn't a native jQuery feature (unless you forgot to load a specific plugin). We'll use standard jQuery AJAX with FormData for reliable file handling.
Full Fixed Code
<!DOCTYPE html> <html> <meta charset="UTF-8"> <body> <form action="API link" class="upload" id="file-upload" method="post" enctype="multipart/form-data"> <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload file" name="submit"> </form> <!-- Load jQuery first to avoid $ undefined errors --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script> $(function() { $('#file-upload').on('submit', function(e) { // Stop the form from reloading the page e.preventDefault(); // Create a FormData object to wrap the file and form data var formData = new FormData(this); // Send the file via AJAX $.ajax({ url: $(this).attr('action'), type: 'POST', data: formData, processData: false, // Don't modify file data contentType: false, // Let the browser set the correct content type for files dataType: 'json', success: function(data) { // Show the server's response in an alert alert(JSON.stringify(data)); // Use data directly if it's a plain string }, error: function(xhr) { // Optional: Handle upload failures alert('Upload failed: ' + xhr.responseText); } }); }); }); </script> </body> </html>
Key Changes Breakdown:
- Reordered script tags to load jQuery before your custom code, fixing the
$undefined error - Added
e.preventDefault()to block the form's default page-jump behavior - Used
FormDatato properly handle file uploads via AJAX - Replaced the non-native
upload()method with standard jQuery$.ajax()for better compatibility - Added basic error handling to catch and report upload failures
内容的提问来源于stack exchange,提问作者Best Jeanist

