EJS中JavaScript函数返回undefined:地址状态校验请求异常
is_address_exist The core problem here is that your is_address_exist function uses an asynchronous XMLHttpRequest, but you're trying to get a return value synchronously. The function finishes running right after calling xmlhttp.send(), long before the server responds — so it returns undefined by default, since there's no explicit return statement that waits for the request to complete.
Why Your Current Code Fails
Looking at your snippet, the onreadystatechange handler only runs after the request finishes, but by that point, the is_address_exist function has already exited. There's no way to "return" the result from that async handler back to the original function call directly.
Solution 1: Use a Callback Function
One classic way to handle async operations is to pass a callback function that gets executed once the request completes:
function is_address_exist(address, callback) { var xmlhttp = new XMLHttpRequest(); var url = '../withdrawn/address_check/' + address; xmlhttp.open('GET', url, true); xmlhttp.send(); xmlhttp.onreadystatechange = function() { // Wait for the request to fully complete (readyState 4) and succeed (status 200) if (xmlhttp.readyState === 4) { if (xmlhttp.status === 200) { // Trim whitespace to avoid unexpected results const addressStatus = xmlhttp.responseText.trim(); // Pass the result to the callback callback(null, addressStatus); } else { // Handle request errors by passing an error to the callback callback(new Error(`Request failed with status: ${xmlhttp.status}`)); } } }; } // How to use it: is_address_exist("your-target-address", function(error, status) { if (error) { console.error("Failed to check address:", error); return; } console.log("Address status:", status); // Will log 'yes' or 'no' });
Solution 2: Use Promises (Modern Approach)
For cleaner code (especially if you're working with other async operations), wrap the request in a Promise. This lets you use async/await for even more readable code:
function is_address_exist(address) { return new Promise((resolve, reject) => { var xmlhttp = new XMLHttpRequest(); var url = '../withdrawn/address_check/' + address; xmlhttp.open('GET', url, true); xmlhttp.send(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState === 4) { if (xmlhttp.status === 200) { const addressStatus = xmlhttp.responseText.trim(); resolve(addressStatus); // Resolve with the result } else { reject(new Error(`Request failed with status: ${xmlhttp.status}`)); // Reject on error } } }; }); } // Using async/await: async function checkAddressStatus() { try { const status = await is_address_exist("your-target-address"); console.log("Address status:", status); // Will log 'yes' or 'no' } catch (error) { console.error("Failed to check address:", error); } } // Call the async function checkAddressStatus();
Important Notes
- If your backend returns JSON instead of plain text (e.g.,
{"status": "yes"}), replacexmlhttp.responseText.trim()withJSON.parse(xmlhttp.responseText).status. - Always handle request errors (like 404 or 500 status codes) — otherwise, you'll get silent failures if the server doesn't respond correctly.
- Ensure there are no CORS issues if your frontend is hosted on a different domain than the backend.
内容的提问来源于stack exchange,提问作者coin-o-pedia c

