【问题标题】:what is xhr.send in this code what works?这段代码中的 xhr.send 是什么?
【发布时间】:2020-10-24 20:50:43
【问题描述】:

大家好,我在这段代码中有一个问题,我不明白 xhr.send() 的工作原理是什么? 因为我的代码没了,我挂了

document.querySelector('.get-jokes').addEventListener('click', getJokes);

function getJokes(e) {
    const number = document.querySelector('input[type="number"]').value;

    const xhr = new XMLHttpRequest();

    xhr.open('GET', `http://api.icndb.com/jokes/random/${number}`, true);

    xhr.onload = function() {
        if (this.status === 200) {
            const response = JSON.parse(this.responseText);

            let output = '';

            if (response.type === 'success') {
                response.value.forEach(function(joke) {
                    output += `<li>${joke.joke}</li>`;
                });
            } else {
                output += '<li>Something went wrong</li>';
            }

            document.querySelector('.jokes').innerHTML = output;
        }
    }

    xhr.send();

    e.preventDefault();
}

【问题讨论】:

  • 你看到docs了吗?

标签: javascript ajax xmlhttprequest send


【解决方案1】:

xhr 是 XMLHttpRequest 的一个实例。 XMLHttpRequest 的 send() 方法将请求发送到服务器。如果请求是异步的,它会在请求发送后立即返回,并使用事件传递结果。在同步情况下,此方法在响应到达之前不会返回。

更多详情,请浏览此link

【讨论】:

    猜你喜欢
    • 2021-07-15
    • 2018-01-23
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    相关资源
    最近更新 更多