如何将Sweet Alert输入框的值保存为JavaScript变量并复用
Hey there! The core issue here is that SweetAlert's swal() function returns a Promise, not the direct input value you're trying to access right away. Since the popup is asynchronous (it waits for user interaction), your console.log runs before the user even enters their input—hence why you're not getting the value correctly.
Let's break down the fixes with two common approaches:
1. Use Promise .then() Method
This is the standard way to handle asynchronous operations with Promises. We'll wait for the user to submit or cancel the input, then act on the result:
function getPrices() { swal("Enter cryptocurrency name", { content: "input" }) .then((result) => { // Make sure the user didn't cancel the popup if (result) { const coinName = result.value; console.log(coinName); // Proceed with your API call $.getJSON( `http://www.whateverorigin.org/get?url=${encodeURIComponent('https://api.coinmarketcap.com/v1/ticker/')}${coinName}`, (data) => { // Handle the retrieved data here console.log("API Response:", data); } ); } else { console.log("User cancelled the input"); } }) .catch((error) => { console.error("Error occurred:", error); }); }
2. Use async/await (Cleaner, More Readable)
If you prefer code that looks synchronous, convert your function to an async function and use await to pause execution until the user provides input:
async function getPrices() { try { const result = await swal("Enter cryptocurrency name", { content: "input" }); // Check if the user submitted input (not cancelled) if (result) { const coinName = result.value; console.log(coinName); // Await the API response (wrap $.getJSON in a Promise to use await) const data = await new Promise((resolve, reject) => { $.getJSON( `http://www.whateverorigin.org/get?url=${encodeURIComponent('https://api.coinmarketcap.com/v1/ticker/')}${coinName}`, resolve ).fail(reject); }); console.log("API Response:", data); } else { console.log("User cancelled the input"); } } catch (error) { console.error("Error occurred:", error); } }
Key Notes:
- When the user submits input, SweetAlert resolves the Promise with an object containing the
valueproperty. - If the user cancels the popup, the Promise either resolves to
nullor rejects (depending on your SweetAlert version)—so always add a check forresultbefore accessingresult.value. - Your original code tried to access
coinName.valueimmediately after callingswal(), butcoinNamewas just a pending Promise, not the input result. That's why it failed!
内容的提问来源于stack exchange,提问作者marsnebulasoup

