通过 XMLHttpRequest 进行内容不敏感自动保存

发布于 2024-11-24 00:05:11 字数 4115 浏览 1 评论 0原文

我正在尝试制作一个自动保存,可以将其放入我的任何表单中,并“自我了解”内容以模拟实际保存。此外,我希望它能够在自动保存多次失败的情况下通知用户。以下是我想出的结果,但由于我的 XMLHttpRequest.send(),我不断获得 readyState = 4 和 status = 500 。当我“通常”单击表单的“保存”时,保存工作完全正常,但此代码似乎无法正确传递数据。每个具有此代码的页面都有一个 setTimeout(autosave,5000) 来初始化代码。有人可以指出我做错的事情的正确方向吗?我是 XMLHttpRequest 对象的新手。

据我所知,last_params 被“发送”了正确的数据,但是当我通过 request()(在另一端使用经典 ASP)获取它时,该值是“”(空白)。我认为我遇到了执行顺序问题,我只是不知道是什么或在哪里。

快速脚注:我知道 jQuery 和其他框架有“类似”的功能,但我对它们还感觉不够舒服。我想从一些“简单”的事情开始。

var last_params = "";
var autosave_time = 61000;

var autosave_fail_check = 5;
var max_autosave_fail_check = 5;

var response_text = "";

function autosave() {

    var autosave_button_name = "save_button";

    var form_action = document.getElementById("formS").action;
    var form_data = document.getElementById("formS");
    var all_inputs = form_data.getElementsByTagName("input");
    var all_textareas = form_data.getElementsByTagName("textarea");

    var params = "";

    // Check all inputs for data        
    for (var i = 0; i < all_inputs.length; i++) {
        var current_item = all_inputs[i];
        if (current_item.type != "button" && current_item.type != "submit") {
            if (current_item.type != "checkbox") {
                params += current_item.name + "=" + current_item.value + "&";

            } else {
                params += current_item.name + "=" + current_item.checked + "&";
            }
        }       
    }

    // check all textareas for data
    for (var i = 0; i < all_textareas.length; i++) {
        var current_item = all_textareas[i];
        params += current_item.name + "=" + current_item.value + "&";
    }

    params += "autosave=1";

    if (params == last_params) {
        setTimeout(autosave, autosave_time);
        return;
    } else {
        last_params = params;
    }

    // Setup time
    var time = "";
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    var seconds = currentTime.getSeconds();

    if (minutes < 10) {
        minutes = "0" + minutes;
    }

    time = hours + ":" + minutes + ":" + seconds;

    if(hours > 11){
        time = time + "PM";
    } else {
        time = time + "AM";
    }

    var status = "[]";

    // **************************************************
    var http;

    try {
      // Gecko-based browsers, Safari, and Opera.
      http = new XMLHttpRequest();
    } catch(e) {
        try {
          // For Internet Explorer.
          http = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {
            // Browser supports Javascript but not XMLHttpRequest.
            document.getElementById(autosave_button_name).value = "Autosave NOT Available";
            http = false;
        }
    }

    http.onreadystatechange = function()
    {
        if (http.readyState == 4 && http.status == 200) {
            autosave_fail_check = max_autosave_fail_check; // reset the fail check
        }
        status = " [" + http.readyState + " / " + http.status + "] ";
    }

    if (autosave_fail_check <= 0) {
        if (autosave_fail_check == 0) {
            document.getElementById(autosave_button_name).value = "Autosave FAILURE; Check Connection!";
            //alert("Autosave has FAILED! Please check your connection!");
        } 

        autosave_fail_check = -1;
    } else {
        autosave_fail_check--;  
    }

    var url = form_action;

    http.open("POST", url, true); // async set to false to prevent moving on without saving
    http.setRequestHeader("Content-type", "multipart/form-data");
    http.setRequestHeader("Content-length", params.length);
    http.setRequestHeader("Connection", "close");
    http.send(last_params);

    response_text = http.responseText;

    if (autosave_fail_check >= 0) {
        document.getElementById(autosave_button_name).value = "Last Saved: " + time + " [" + autosave_fail_check + "] " + status;
    } else {
        autosave_fail_check = -1;   
    }

    setTimeout(autosave, autosave_time);

} // end function autosave()

I am trying to make an autosave that can be dropped into any of my forms and be "self aware" of the content in order to simulate an actual save. In addition, I want it to be able to notify the user in the event of multiple failures of the autosave. The following is the come I have come up with, but I keep getting readyState = 4 and status = 500 as a result of my XMLHttpRequest.send(). When I "normally" click save with the form, the save works perfectly fine, but this code just doesn't seem to pass the data over correctly. Every page that has this code has a setTimeout(autosave,5000) to initialize the code. Can someone point me in the right direction of what I'm doing wrong? I'm new to XMLHttpRequest objects.

For what I can tell, last_params gets "sent" with the correct data, but when I get it via the request() (using classic ASP on the other end), the value is "" (blank). I'm thinking I have an order of execution problem, I just don't know what or where.

Quick footnote: I know that there are 'similar' functions with jQuery and other frameworks, but I do not feel comfortable enough with them yet. I want to start with something "simple".

var last_params = "";
var autosave_time = 61000;

var autosave_fail_check = 5;
var max_autosave_fail_check = 5;

var response_text = "";

function autosave() {

    var autosave_button_name = "save_button";

    var form_action = document.getElementById("formS").action;
    var form_data = document.getElementById("formS");
    var all_inputs = form_data.getElementsByTagName("input");
    var all_textareas = form_data.getElementsByTagName("textarea");

    var params = "";

    // Check all inputs for data        
    for (var i = 0; i < all_inputs.length; i++) {
        var current_item = all_inputs[i];
        if (current_item.type != "button" && current_item.type != "submit") {
            if (current_item.type != "checkbox") {
                params += current_item.name + "=" + current_item.value + "&";

            } else {
                params += current_item.name + "=" + current_item.checked + "&";
            }
        }       
    }

    // check all textareas for data
    for (var i = 0; i < all_textareas.length; i++) {
        var current_item = all_textareas[i];
        params += current_item.name + "=" + current_item.value + "&";
    }

    params += "autosave=1";

    if (params == last_params) {
        setTimeout(autosave, autosave_time);
        return;
    } else {
        last_params = params;
    }

    // Setup time
    var time = "";
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    var seconds = currentTime.getSeconds();

    if (minutes < 10) {
        minutes = "0" + minutes;
    }

    time = hours + ":" + minutes + ":" + seconds;

    if(hours > 11){
        time = time + "PM";
    } else {
        time = time + "AM";
    }

    var status = "[]";

    // **************************************************
    var http;

    try {
      // Gecko-based browsers, Safari, and Opera.
      http = new XMLHttpRequest();
    } catch(e) {
        try {
          // For Internet Explorer.
          http = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {
            // Browser supports Javascript but not XMLHttpRequest.
            document.getElementById(autosave_button_name).value = "Autosave NOT Available";
            http = false;
        }
    }

    http.onreadystatechange = function()
    {
        if (http.readyState == 4 && http.status == 200) {
            autosave_fail_check = max_autosave_fail_check; // reset the fail check
        }
        status = " [" + http.readyState + " / " + http.status + "] ";
    }

    if (autosave_fail_check <= 0) {
        if (autosave_fail_check == 0) {
            document.getElementById(autosave_button_name).value = "Autosave FAILURE; Check Connection!";
            //alert("Autosave has FAILED! Please check your connection!");
        } 

        autosave_fail_check = -1;
    } else {
        autosave_fail_check--;  
    }

    var url = form_action;

    http.open("POST", url, true); // async set to false to prevent moving on without saving
    http.setRequestHeader("Content-type", "multipart/form-data");
    http.setRequestHeader("Content-length", params.length);
    http.setRequestHeader("Connection", "close");
    http.send(last_params);

    response_text = http.responseText;

    if (autosave_fail_check >= 0) {
        document.getElementById(autosave_button_name).value = "Last Saved: " + time + " [" + autosave_fail_check + "] " + status;
    } else {
        autosave_fail_check = -1;   
    }

    setTimeout(autosave, autosave_time);

} // end function autosave()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文