You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过JavaScript实现从控制器获取数据动态创建Feed帖子?

How to Dynamically Fetch User Data from Backend for Feed Posts

Hey there! Let's figure out how to replace those hardcoded user details (like username and avatar) with real data from your backend. Here's a straightforward approach with revised code to make this work:

Step 1: Set Up Your Backend Endpoint

First, you'll need a backend endpoint that returns the current user's data in JSON format. For example, a GET request to /api/current-user should return something like:

{
  "username": "Dr. John Cook PhD",
  "department": "Human Resources & Psychiatry Division",
  "avatarUrl": "/assets/images/profiles/john-cook.jpg",
  "postTime": "3 hours ago"
}

Step 2: Fetch User Data in JavaScript

Use either jQuery (since your code already uses it) or native fetch to grab this data from your backend. We'll wrap this in a reusable function:

Option 1: Using jQuery AJAX

function getUserData() {
  return $.ajax({
    url: '/api/current-user', // Replace with your actual endpoint
    method: 'GET',
    dataType: 'json'
  });
}

Option 2: Using Native Fetch (Async/Await)

async function getUserData() {
  try {
    const response = await fetch('/api/current-user');
    if (!response.ok) throw new Error('Failed to load user data');
    return await response.json();
  } catch (error) {
    console.error('Error fetching user data:', error);
    // Fallback to default data if the request fails
    return {
      username: 'Guest User',
      department: 'Unknown Department',
      avatarUrl: '',
      postTime: 'Just now'
    };
  }
}

Step 3: Refactor Post Creation Logic

We'll clean up your existing code to use the dynamic user data, fix duplicate event bindings, and use template literals for cleaner HTML structure:

Revised HTML (Remove Duplicate Onclick)

<body> 
  <textarea class="form-control border-0 p-0 fs-xl" rows="4" id="input" placeholder="What's on your mind Codex?..."></textarea> 
  <button class="btn btn-info shadow-0 ml-auto " id="submit">Post</button> 
  <div id="add_after_me"> 
    <div class="test"></div> 
  </div> 
  <script>
    // Your updated JavaScript goes here
  </script>
</body>

Updated JavaScript

// Refactored post creation function
async function addCode() {
  // Get user data from backend
  const userData = await getUserData();
  // Get post content from textarea
  const postContent = $('#input').val().trim();

  // Validate input
  if (!postContent) {
    alert('Please enter content for your post!');
    return;
  }

  // Use template literals for readable HTML
  const postHtml = `
    <div class="card mb-g">
      <div class="card-body pb-0 px-4">
        <div class="d-flex flex-row pb-3 pt-2 border-top-0 border-left-0 border-right-0">
          <div class="d-inline-block align-middle status status-success mr-3">
            <span class="profile-image rounded-circle d-block" style="background-image:url(${userData.avatarUrl}); background-size: cover;"></span>
          </div>
          <h5 class="mb-0 flex-1 text-dark fw-500">${userData.username} 
            <small class="m-0 l-h-n">${userData.department}</small>
          </h5>
          <span class="text-muted fs-xs opacity-70">${userData.postTime}</span>
        </div>
        <div class="pb-3 pt-2 border-top-0 border-left-0 border-right-0 text-muted">
          ${postContent}
        </div>
      </div>
    </div>
  `;

  // Insert the new post into the feed
  document.getElementById("add_after_me").insertAdjacentHTML("afterend", postHtml);
  
  // Clear the textarea after posting
  $('#input').val('');
}

// Bind click event properly (no more inline onclick)
$(document).ready(function() {
  $('#submit').click(addCode);
});

Additional Tips

  • Prevent Duplicate Posts: Disable the "Post" button while the request is in flight to avoid multiple submissions.
  • Sanitize Content: If you're allowing HTML in posts, use a sanitization library or convert content to plain text to prevent XSS attacks.
  • Loading States: Add a loading spinner while fetching user data to improve user experience.

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

火山引擎 最新活动