简体   繁体   English

如何使用ajax更改此变量?

[英]How can I change this variable with ajax?

I'm curious as to why this isn't working, here's the code: 我很好奇为什么这不起作用,下面是代码:

function Ajax(sUrl, fCallback) {

    var url = sUrl || '';
    var callback = fCallback || function () {};
    var xmlhttp = (function () {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try {
                return new ActiveXObject("Msxml2.XMLHTTP.6.0");
            } catch (e) {
                try {
                    return new ActiveXObject("Msxml2.XMLHTTP.3.0");
                } catch (err) {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }
            }
        } else {
            return null;
        }
    }());

    this.setUrl = function (newUrl) {
        url = newUrl;
    };

    this.setCallback = function (func) {
        callback = func;
    };

    this.request = function (method, data) {
        if (xmlhttp === null) { return false; }

        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState === 4) {
                callback(xmlhttp.status, xmlhttp.responseXML, xmlhttp.responseText);
            }
        };

        data = data || '';
        data = encodeURIComponent(data);
        if ((/post/i).test(method)) {
            xmlhttp.open('POST', url);
            xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlhttp.send(data);
        } else {
            var uri = data === '' ? url : url + '?' + data;
            xmlhttp.open('GET', uri);
            xmlhttp.send();
        }

        return true;
    };

    return this;

}

var ajax = new Ajax(''); // sets the url, not necessary for this demonstration
var changed = false;

function change() {
    changed = true;
}

function foo() {
    ajax.setCallback(change);
    ajax.request();
    alert(changed);
}

foo();

There is a fiddle here: http://jsfiddle.net/dTqKG/ 这里有一个小提琴: http : //jsfiddle.net/dTqKG/

I feel like the change function would create a closure that would indeed change the changed variable. 我觉得change函数将创建一个确实会更改changed变量的闭包。 Does anyone know what's going on? 有人知道发生了什么吗?

The ajax.request(); ajax.request(); will return before change() is called. 将在调用change()之前返回。 That is the async nature of the AJAX calls, and the reason why you need the callback as opposed to just getting return value from send() method. 这就是AJAX调用的异步性质,也是您需要回调而不是仅仅从send()方法获取返回值的原因。
Other than that there might be some other issues in the code. 除此之外,代码中可能还存在其他问题。 I question why wouldn't you use one of the many AJAX frameworks readily available instead of writing your own. 我质疑为什么您不使用现成的许多AJAX框架之一而不是编写自己的框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM