同页PHP+AJAX代码表现差异原因咨询:表单提交后显示JSON而非控制台输出
Let's break down exactly what's causing the unexpected behavior in your first page—there are two critical issues in its code that are throwing things off:
1. Typo in the AJAX Callback Name
Take a close look at your first page's AJAX code: you wrote sucess instead of success for the callback parameter.
// Wrong spelling here! sucess: function(data) { console.log(data); }
jQuery doesn't recognize the misspelled sucess property, so it ignores this callback entirely. That means when the AJAX request finishes, there's no code to handle the JSON response and log it to the console.
2. You Didn't Block the Form's Default Submission Behavior
Your first page binds the AJAX call to the form's submit event, but you never tell the browser to skip its default form-submission behavior. By default, when a form is submitted, the browser will reload the page (or navigate to the form's action URL) and display whatever the server returns—in this case, your raw JSON data.
In contrast, your second page's AJAX call is triggered by a custom loadInfo() function, not a form submit event. There's no default browser behavior interfering here, so the AJAX works as expected.
Fix for the First Page
Update your JavaScript to fix the typo and prevent the default form submission:
jQuery(function($) { $("#idSearch").submit(function(event) { // Stop the browser from submitting the form normally event.preventDefault(); $.ajax({ url: "/index.php", type: "POST", data: $(this).serialize(), dataType: "json", // Fixed callback spelling success: function(data) { console.log(data); } }); }); });
With these two changes, the form will no longer reload the page, and the JSON response will be logged to the console just like your second page.
内容的提问来源于stack exchange,提问作者pp182

