如何在jQuery load()执行完成后返回刷新后的CSRF令牌值?
Ah, I get it—you're hitting the classic asynchronous JavaScript snag with jQuery's .load()! Let me break down what's happening and fix it for you.
Why this is happening
Your getCsrfToken function returns before the .load() callback runs. That's because .load() is asynchronous—it sends the request in the background, and your code keeps moving forward. By the time you hit return csrfToken, the callback hasn't updated the variable yet, so you're getting null (or undefined if the text grab fails later).
Solution 1: Use a callback function (traditional approach)
Instead of trying to return the token directly, pass in a function that will handle the token once it's ready:
function getCsrfToken(callback) { $("#csrf-token").load(location.href + " #csrf-token", function () { // Trim to avoid accidental whitespace messing things up const csrfToken = $("#csrf-token").text().trim(); callback(csrfToken); }); } // How to use it: getCsrfToken(function(newToken) { console.log("Fresh CSRF token:", newToken); // Put all your logic that needs the token right here—like making an API request });
Solution 2: Use Promises + async/await (modern, cleaner approach)
If you prefer writing code that looks more synchronous, wrap the .load() call in a Promise. This lets you use async/await to wait for the token:
function getCsrfToken() { return new Promise((resolve, reject) => { $("#csrf-token").load(location.href + " #csrf-token", (response, status, xhr) => { if (status === "success") { const csrfToken = $("#csrf-token").text().trim(); resolve(csrfToken); } else { reject(new Error(`Failed to load CSRF token: ${xhr.statusText}`)); } }); }); } // How to use it (needs to be inside an async function): async function useFreshCsrfToken() { try { const newToken = await getCsrfToken(); console.log("Fresh CSRF token:", newToken); // Do your work with the token here—no callback nesting! } catch (error) { console.error("Oops, something went wrong:", error); } } // Call the async function useFreshCsrfToken();
Quick tips to avoid headaches
- Always use
.trim()when grabbing text from the DOM—extra spaces can break token validation. - If your backend serves the CSRF token in a
<meta>tag (common in frameworks like Rails, Django, Laravel), you don't even need to reload the div! Just grab it directly:const csrfToken = document.querySelector('meta[name="csrf-token"]').content; - Double-check that
location.href + " #csrf-token"actually returns the element you need—if the request fails or the selector is wrong, your token will be empty.
内容的提问来源于stack exchange,提问作者Silas de Rooy

