You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中jQuery POST请求响应无法渲染页面问题求助

Hey there! Let's figure out why your page isn't updating after the POST request, and fix it step by step.

The Root Problem

Right now, your AJAX request sends the form data to the backend, and the backend returns a fully rendered profile.ejs page with the "Changes Updated" message. But your frontend code doesn't do anything with that returned HTML—AJAX won't automatically refresh or replace your page content unless you explicitly tell it to. The success callback in your $.ajax call is empty, so the response just gets ignored.

This is a cleaner approach that separates frontend and backend concerns. We'll have the backend return a JSON status message, then use JavaScript to update the DOM directly.

Step 1: Update the Backend (Index.js)

First, modify your POST route to return JSON instead of rendering the entire page. Also, don't forget to actually update the user's data in your database (you're missing that part right now—otherwise the changes won't persist!).

// Assuming you have a User model set up (e.g., with Mongoose)
router.post('/profile', loggedin, async function(req, res, next) {
  try {
    // Update the logged-in user's profile with the submitted data
    await User.findByIdAndUpdate(req.user._id, req.body, { new: true });
    // Return a success status as JSON
    res.json({ status: 'Changes Updated' });
  } catch (err) {
    // Handle errors and return an error message
    res.json({ status: `Update Failed: ${err.message}` });
  }
});

Step 2: Update the Frontend (Profile.ejs)

Modify the AJAX success callback to take the JSON response and update the #res div's content:

$.ajax({
  type: "POST",
  url: "/profile",
  data: json,
  success: function(response) {
    // Update the status message in the #res div
    document.getElementById('res').querySelector('h4').textContent = response.status;
    // Optional: Clear the form after successful submission
    document.getElementById('test').reset();
  },
  dataType: "json",
  contentType: "application/json"
});

Fix 2: Replace Page Content with Returned HTML (Quick Fix)

If you want to keep the backend returning the full rendered page, you can have the frontend replace the current page's content with the returned HTML:

$.ajax({
  type: "POST",
  url: "/profile",
  data: json,
  success: function(html) {
    // Replace the entire body with the new rendered HTML
    document.body.innerHTML = html;
  },
  // Change dataType to html (or let jQuery auto-detect)
  dataType: "html",
  contentType: "application/json"
});

Key Things to Note

  • Database Updates: Your original code doesn't save the user's changes to the database—make sure to add that logic using your ORM/ODM (like Mongoose for MongoDB) so the updates persist across sessions.
  • AJAX Basics: Always handle the success (and error) callbacks—AJAX requests are asynchronous, so you need to define what happens once the response comes back.

Learning Resources to Level Up

Since you're new to this, here are some topics to focus on:

  • AJAX & Asynchronous JS: Learn how AJAX works under the hood (start with native XMLHttpRequest, then move to jQuery AJAX or modern fetch API). Understand async/await for handling asynchronous operations.
  • Express.js Fundamentals: Dive into routing, request/response handling, and how template engines like EJS work. Learn when to return JSON vs. rendered HTML.
  • DOM Manipulation: Master how to modify HTML elements with vanilla JavaScript—this is essential for updating page content dynamically.
  • Full-Stack Data Flow: Study how frontend and backend communicate, including RESTful API design and how to send/receive data between them.

内容的提问来源于stack exchange,提问作者Wisam Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:18:12