编写XHR同步行为的其他方法 [英] Alternative Ways To Write XHR Synchronous Behavior

查看:263
本文介绍了编写XHR同步行为的其他方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近听说我们不会在使用XHR时使用同步行为。在我的情况下,我需要同步行为。什么是重写我的服务调用的最佳方式同步而不是我现在如何做。请不要jquery ..

I recently heard we are not suppose to using Synchronous behavior when using XHR. In my case I need Synchronous behavior. What is the best way to rewrite my calls to my services Synchronously instead of how I am doing it now. No jquery please ..

   var xhReq = new XMLHttpRequest();
    xhReq.open("POST", "ClientService.svc/REST/TestHtmlSend", false);
    xhReq.send(null);
    var serverResponse = JSON.parse(xhReq.responseText);

    return serverResponse;


推荐答案

你永远需要同步行为;相反,你(开发人员)只需要围绕JavaScript的异步性质–具体来说,如何使用匿名回调和处理闭包。

You never need "synchronous behavior"; instead, you (the developer) just have to wrap your head around JavaScript's asynchronous nature – specifically, how to use anonymous callbacks and deal with closures.

例如,如果你这样做:

function doSomething(arg) {
    var number = arg + 10; // for example
    var data = getDetail();
    data = JSON.parse(data);
    element.innerHTML = number + ': ' + data.name;
}

function getDetail() {
    var xhReq = new XMLHttpRequest();
    xhReq.open("POST", "ClientService.svc/REST/GetDetail", false); // bad!
    xhReq.send(null);
    return xhReq.responseText;
}

可以异步编写:

function doSomething(arg) {
    var number = arg + 10;
    getDetail(function(data) {
        data = JSON.parse(data);
        element.innerHTML = number + ': ' + data.name;
    });
}

function getDetail(cb) {
    var xhReq = new XMLHttpRequest();
    xhReq.open("POST", "ClientService.svc/REST/GetDetail", true);
    xhReq.onreadystatechange = function() {
        if (xhReq.readyState == 4) cb(xhReq.responseText);
    }
    xhReq.send(null);
}

请注意,在异步示例中,您的内部回调函数(仅在网络请求已完成)仍然可以访问外部函数的数字变量。这是因为JavaScript具有静态范围–换句话说,当你声明一个函数时,该函数将永久地访问包含该函数的任何函数的变量。

Notice in the asynchronous example that your inner callback function (which executes only after the network request has completed) still has access to the outer function's number variable. This is because JavaScript has static scope – in other words, when you declare a function, that function will permanently have access to the variables of any functions that enclose that function.

这篇关于编写XHR同步行为的其他方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆