【问题标题】:How can I return custom response from XMLHTTP request?如何从 XMLHTTPrequest 返回自定义响应?
【发布时间】:2019-10-28 15:53:54
【问题描述】:

从股票 API 中提取数据,获取所有交易品种名称。我从 HTML 输入中获取一个字符串符号并使用该值来匹配从 API 中提取的符号。

如果找到,我希望返回一个简单的布尔值,我已将其添加到 request.onload 方法中。当我从另一个方法调用/获取响应时,我会看到对象的未定义或文本响应。

我在按钮单击侦听器中添加了一个“加载”事件侦听器,我尝试在 request.send 方法中添加布尔变量,我添加了一个就绪状态更改侦听器,它似乎有帮助但没有响应类型从 onload 方法返回布尔变量。


const searchInput = document.getElementById("symbol-search-input");
const symbolSearchBtn = document.getElementById("symbol-search-btn");
const symbolSearchMsg = document.getElementById("symbol-status-msg");
const request = new XMLHttpRequest();

symbolSearchBtn.addEventListener("click", () => {

    //Value from html input
    let symbolSearch = searchInput.value;

    if(symbolSearch == "") {
        symbolSearchMsg.innerHTML = "symbol field blank";

    } else {
        //calling XMLHTTPRequest to begin the process
        symbolFound();

        request.onreadystatechange = () => {
            if(request.readyState == 4) {

                if(request.status == 200) {
                    //Below it only returns the entire JSON as text even if I only use "request.response"
                    console.log(request.responseText);

                }

                if(request.status == 404) {
                    console.log('File or resource not found');
                }

            }
        };


let symbolFound = () => {

    request.open('GET', 'https://api.iextrading.com/1.0/ref-data/symbols', true);
    let foundSymbol = false;

    request.onload = function() {
        let data = JSON.parse(this.response);

        if(request.status >= 200 && request.status < 400) {
            let symbolInput = searchInput.value.toUpperCase();

            for(let i = 0; i < data.length; i++) {
                if(data[i]['symbol'] === symbolInput) {
                    foundSymbol = true;
                    break;
                }
            }
            return foundSymbol;

        } else {
            console.log("error");
        }
    };

    request.send();
};


我希望收到布尔返回(真或假),相反,我从 API 接收 JSON 作为文本/字符串。

【问题讨论】:

  • 试试request.send(foundSymbol);
  • 我试过了,但没有运气。我仍然收到 JSON 作为文本。
  • 你想返回foundSymbol 的布尔值吗? responseText 返回字符串 - developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…。您可以通过将其 responseType 设置为 json - developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/… 来返回对象中的响应。您不能返回布尔值,而是可以将字符串发送为“true”或“false”。
  • 我不确定我是否完全理解,我对 web 开发还是比较陌生,所以也许我很困惑。第一个链接表明我只会从服务器接收响应对象。如果我理解正确,您似乎是在说我不能接收一个布尔值,我可以接受,而是必须接收一个字符串。我可以接收字符串响应,但是如何接收自定义字符串?你能提供一个代码示例吗?我不确定我是否知道如何执行/完成您的意思。

标签: javascript ajax api xmlhttprequest


【解决方案1】:

我想出了如何做到这一点,至少是一种解决方法。我没有返回任何值,而是简单地让它改变一个变量的状态并调用另一个函数来做我需要的布尔值。这也是剖析初始功能的问题。看看吧。

const searchInput = document.getElementById("symbol-search-input");
const symbolSearchBtn = document.getElementById("symbol-search-btn");
const symbolSearchMsg = document.getElementById("symbol-status-msg");
let isSymbolFound;


symbolSearchBtn.addEventListener("click", () => {

    let symbolSearch = searchInput.value;

    if(symbolSearch == "") {
        symbolSearchMsg.innerHTML = "symbol field blank";

    } else {
        isSymbolFound = false;
        const xhr = new XMLHttpRequest();
        xhrProcess(xhr);

        xhr.onload = function() {
            let data = JSON.parse(this.response);

            if(xhr.status >= 200 && xhr.status < 400) {
                let symbolInput = symbolSearch.toUpperCase();

                for(let i = 0; i < data.length; i++) {
                    if(data[i]['symbol'] === symbolInput) {
                        isSymbolFound = true;
                        break;
                    }
                }
                symbolFindProcess();

            } else {
                console.log("error");
            }
        };
    }
});

const symbolFindProcess = () => {
    if(isSymbolFound) {
        //code here
    } else {
        //code here
    }
};

const xhrProcess = (request) => {
    request.open('GET', 'https://api.iextrading.com/1.0/ref-data/symbols', true);
    request.send();
};


【讨论】:

    猜你喜欢
    • 2016-12-14
    • 2021-08-27
    • 1970-01-01
    • 2021-01-08
    • 2017-03-26
    • 2021-05-10
    • 2021-07-13
    • 2020-04-23
    • 2021-11-11
    相关资源
    最近更新 更多