我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?

我需要在Mac OS X的dashcode小部件中做到这一点。


当前回答

你可以通过两种方式获得HTTP get请求:

该方法基于xml格式。您必须为请求传递URL。 xmlhttp.open(“获得”、“URL”,真正的); xmlhttp.send (); 它是基于jQuery的。您必须指定要调用的URL和function_name。 $ (btn) .click(函数(){ 美元。Ajax ({url: "demo_test.txt", success: function_name(result) { $ (" # innerdiv ") . html(结果); }}); });

其他回答

// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'restUrl', true)

request.onload = function () {
  // Begin accessing JSON data here
}

// Send request
request.send()

我不熟悉Mac OS的Dashcode小部件,但如果他们让你使用JavaScript库和支持xmlhttprequest,我会使用jQuery,做这样的事情:

var page_content;
$.get( "somepage.php", function(data){
    page_content = data;
});

一种支持旧浏览器的解决方案:

function httpRequest() {
    var ajax = null,
        response = null,
        self = this;

    this.method = null;
    this.url = null;
    this.async = true;
    this.data = null;

    this.send = function() {
        ajax.open(this.method, this.url, this.asnyc);
        ajax.send(this.data);
    };

    if(window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    }
    else if(window.ActiveXObject) {
        try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP.6.0");
        }
        catch(e) {
            try {
                ajax = new ActiveXObject("Msxml2.XMLHTTP.3.0");
            }
            catch(error) {
                self.fail("not supported");
            }
        }
    }

    if(ajax == null) {
        return false;
    }

    ajax.onreadystatechange = function() {
        if(this.readyState == 4) {
            if(this.status == 200) {
                self.success(this.responseText);
            }
            else {
                self.fail(this.status + " - " + this.statusText);
            }
        }
    };
}

这段代码可能有点过分,但绝对是安全的。

用法:

//create request with its porperties
var request = new httpRequest();
request.method = "GET";
request.url = "https://example.com/api?parameter=value";

//create callback for success containing the response
request.success = function(response) {
    console.log(response);
};

//and a fail callback containing the error
request.fail = function(error) {
    console.log(error);
};

//and finally send it away
request.send();

在纯javascript和返回一个承诺:

  httpRequest = (url, method = 'GET') => {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open(method, url);
      xhr.onload = () => {
        if (xhr.status === 200) { resolve(xhr.responseText); }
        else { reject(new Error(xhr.responseText)); }
      };
      xhr.send();
    });
  }

下面是直接用JavaScript实现的代码。但是,如前所述,使用JavaScript库会更好。我最喜欢jQuery。

在下面的例子中,调用一个ASPX页面(作为穷人的REST服务)来返回一个JavaScript JSON对象。

var xmlHttp = null;

function GetCustomerInfo()
{
    var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
    var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = ProcessRequest;
    xmlHttp.open( "GET", Url, true );
    xmlHttp.send( null );
}

function ProcessRequest() 
{
    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
    {
        if ( xmlHttp.responseText == "Not found" ) 
        {
            document.getElementById( "TextBoxCustomerName"    ).value = "Not found";
            document.getElementById( "TextBoxCustomerAddress" ).value = "";
        }
        else
        {
            var info = eval ( "(" + xmlHttp.responseText + ")" );

            // No parsing necessary with JSON!        
            document.getElementById( "TextBoxCustomerName"    ).value = info.jsonData[ 0 ].cmname;
            document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
        }                    
    }
}