【问题标题】:Adding image depends on ajax response添加图像取决于ajax响应
【发布时间】:2020-12-01 02:25:50
【问题描述】:

我正在使用 ajax 调用从公共 API 获得响应。我想显示图像取决于此响应。但我无法指定响应或在 ajax 调用之外创建条件(无法读取)。我该怎么做?

【问题讨论】:

标签: javascript html ajax web


【解决方案1】:

您好,我认为promise 可以帮助您解决这个问题。
我已尝试解释 sn-p 中显示的所有代码。
阅读更多关于promisehere on MDN

const content = document.getElementById('content');

async function callAjax(req) {
  let promise = new Promise((res, rej) => {
    // setTimeout is your ajax call where you have to wait
    window.setTimeout(() => {
      if (req === 'yourAjaxCall') {
        console.log('ajax success')
        // use when you know the ajax call is a success
        res({ content: 'success' });
        // use rej() if the ajax call is rejected
      }
    }, 1000);
  })
  
  return promise
}

async function run() {
  console.log('run')
  const sucsess = await callAjax('yourAjaxCall')

  content.innerHTML = `${sucsess.content}`
}

run()
<div id="content"><div>

【讨论】:

    【解决方案2】:

    例如,如果您使用 jQuery,则需要在回调函数中获取 HTML 元素。例如:

    $(function() {
      $.get("http://yoururlapi", (data) => {
         const container = document.getElementById("container");
         container.append(`
            <img src="${data.imageUrl}" alt="Image alt" />
         `);
      });
    })();
    &lt;div id="container"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 2019-07-04
      • 1970-01-01
      相关资源
      最近更新 更多