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

如何将Sweet Alert输入框的值保存为JavaScript变量并复用

Fixing SweetAlert Input Value Retrieval

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 value property.
  • If the user cancels the popup, the Promise either resolves to null or rejects (depending on your SweetAlert version)—so always add a check for result before accessing result.value.
  • Your original code tried to access coinName.value immediately after calling swal(), but coinName was just a pending Promise, not the input result. That's why it failed!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:55:15