Javascript-XMLHttpRequest需要处理两次

时间:2018-10-02 17:03:53

标签: javascript ajax xmlhttprequest

我正在使用XMLHttpRequest读取上载到我们网站的文本文件,并将该文本添加到电子邮件中。它总是在第二次运行中成功,但没有成功。在打开和关闭电子邮件之前,readyState不会达到4,因此该文本将在第二次打开电子邮件时显示。 (当按下按钮时,sendEmail功能将运行)。我怀疑当电子邮件第二次打开时,它正在获取第一轮数据。 是否可以在第一个请求上运行它?

    function sendEmail() {
        var greeting = "email greeting ";
        var email = "mailto:info@email.com";
        var subject = "?subject=Subject";
        var body = "&body=";

        var code = "some type of model code";

        getPartNumber(code);

        var pn = document.getElementById("part_number").innerHTML;

        window.location.href = email + subject + body + greeting + code + "." + "%0A" + pn;
    }

    function getPartNumber(code) {
        //file address is chosen based on what "code" is, but is a test file for now
        var file_address = "http://[address where file is located].txt";

        var data = new XMLHttpRequest();
        data.onreadystatechange = function () {
            if(data.readyState == 4 && data.status == 200) {
                document.getElementById("part_number").innerHTML = data.responseText;
            }
            //for debugging purposes
            //readyState reaches 2 and status reaches 200 first time email is opened
            //readyState reaches 4 and status reaches 200 after email is closed
            alert("ready state " + data.readyState + " status " + data.status);
        };

        data.open("GET", file_address, true);
        data.send(null);
    }

1 个答案:

答案 0 :(得分:0)

getPartNumber 中的

代码发送异步请求,因此pn不会是您想要的值。尝试使用回调函数 Promise 处理这种情况。