Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - Why do we pass null to XMLHttpRequest.send?

Why is send so often called as

xhr.send(null)

instead of

xhr.send()

?

W3, MDN, and MSDN all state that it's optional. Furthermore, the ActiveX control doesn't seem to need the argument:

hr=pIXMLHTTPRequest.CreateInstance("Msxml2.XMLHTTP.6.0");
SUCCEEDED(hr) ? 0 : throw hr;

hr=pIXMLHTTPRequest->open("GET", "http://localhost/books.xml ", false);
SUCCEEDED(hr) ? 0 : throw hr;

hr=pIXMLHTTPRequest->send(); // <-- this line
SUCCEEDED(hr) ? 0 : throw hr;

The practice of send(null) goes back at least as far as 2005 in Google Maps, but being minified, there's no explanation:

Y.asynchronousTransform = function (qc, vb, kc, Nc, Ba) {
    if (m.type == 3) return;
    var cc = Y.getCached(kc);
    if (cc) {
        cc.transformToHTML(qc, vb);
        if (Nc) Nc();
        return
    }
    var yc = qa.create(Ba);
    var sa = Xd.create();
    nd('<a href="' + kc.xmlEscape() + '">' + kc.xmlEscape() + "</a>", 0);
    sa.open("GET", kc, true);
    sa.onreadystatechange = function () {
        if (sa.readyState == 4) {
            if (yc.isValid()) {
                try {
                    var Db = sa.responseXML;
                    var cc = Y.create(Db);
                    Y.cache(kc, cc);
                    cc.transformToHTML(qc, vb);
                    if (Nc) Nc()
                } catch (b) {}
            }
        }
    };
    sa.send(null)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you'll take a look at an old specification of XMLHttpRequest, it seems like as though the W3C did not require that the parameter be optional at one point, which may have led to people supplying an explicit null value 'just in case'.

(search for 'SHOULD support the send') http://web.archive.org/web/20060409155734/http://www.w3.org/TR/XMLHttpRequest/

Another plausible reason I've come across comes from a translation of a russian page, viewable here: long Google Translate link (search for 'GET-Request for Version without ActiveX')

When you send a GET-request for version without ActiveX, you must specify null, otherwise you can not specify any parameters. Will not fail if GET is always specified null:

I have no idea if this is true or not but it seems plausible that if the GET parameters were included in the body, that the body may not have been generated if the data value was 'undefined'.

Unfortunately, I was unable to find anything more conclusive in my search.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...