Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - JavaScript中的HTTP GET请求?(HTTP GET request in JavaScript?)

I need to do an HTTP GET request in JavaScript.

(我需要在JavaScript中执行HTTP GET请求。)

What's the best way to do that?

(最好的方法是什么?)

I need to do this in a Mac OS X dashcode widget.

(我需要在Mac OS X破折号小部件中执行此操作。)

  ask by mclaughlinj translate from so

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

1 Answer

0 votes
by (71.8m points)

Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:

(浏览器(和Dashcode)提供XMLHttpRequest对象,该对象可用于从JavaScript发出HTTP请求:)

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

However, synchronous requests are discouraged and will generate a warning along the lines of:

(但是,不鼓励同步请求,并且将按照以下方式生成警告:)

Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.

(注意:从Gecko 30.0(Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)开始,由于对用户体验的负面影响, 不赞成在主线程上执行同步请求 。)

You should make an asynchronous request and handle the response inside an event handler.

(您应该发出异步请求并在事件处理程序中处理响应。)

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...