简单的javascript beforeSend和成功

时间:2015-03-20 10:12:32

标签: javascript jquery

在jQuery中,当有东西加载时我可以这样做:

$.ajax({
  url: "/answer_checker.php",
  global: false, type: "POST", 
  data: ({...clipped...}), 
  cache: false,
  beforeSend: function() {
    $('#response').html("<img src='/images/loading.gif' />");
  },
  success: function(html) {
    $('#response').html(html);
  }
}

如何在普通javascript中应用beforeSend和success?我目前有这个:

function processGeneric() {
setTimeout(function () {
    if (xmlHttpObject.readyState === 0 || xmlHttpObject.readyState === 4) {
        xmlHttpObject.open("GET", requestLink, true);
        xmlHttpObject.onreadystatechange = function () {//some code to handle here};
        xmlHttpObject.send(null);
    }
}, timeout);
}

1 个答案:

答案 0 :(得分:2)

您创建一个函数,接受您想要的回调以及其他ajax选项,然后使用该函数:

  1. 在发送&#34;之前调用&#34;回调

  2. 拨打ajax电话,which is well-covered in this other question and its answers

  3. 通话结束后,请致电完成回叫

  4. 这些方面含糊不清:

    function processGeneric(url, beforeSend, completion) {
        var xhr;
    
        xhr = new XMLHttpRequest();
        xhr.onreadstatechange = function() {
            if (xhr.readyState === 0 || xhr.readyState === 4) {
                if (completion) {
                    completion(xhr);
                }
                done();
            }
        };
        xhr.open("GET", url, true);
        if (beforeSend) {
            if (beforeSend(xhr) === false) {
                done();
                return;
            }
        }
        xhr.send(null);
        return xhr;
    
        function done() {
            xhr.onreadystatechange = null;
            xhr = undefined;
        }
    }