Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/430.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript中的HTTP GET请求?_Javascript_Http Get_Dashcode - Fatal编程技术网

JavaScript中的HTTP GET请求?

JavaScript中的HTTP GET请求?,javascript,http-get,dashcode,Javascript,Http Get,Dashcode,我需要用JavaScript做一个请求。最好的方法是什么 我需要在Mac OS X dashcode小部件中执行此操作。 最好使用或之类的库。下面是直接用JavaScript实现的代码。但是,正如前面提到的,使用JavaScript库会更好。我最喜欢的是jQuery 在下面的例子中,调用一个ASPX页面(作为穷人的REST服务)来返回一个JavaScript JSON对象 var xmlHttp = null; function GetCustomerInfo() { var Cust

我需要用JavaScript做一个请求。最好的方法是什么

我需要在Mac OS X dashcode小部件中执行此操作。


最好使用或之类的库。

下面是直接用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;
        }                    
    }
}
让事情变得非常简单

new Ajax.Request( '/myurl', {
  method:  'get',
  parameters:  { 'param1': 'value1'},
  onSuccess:  function(response){
    alert(response.responseText);
  },
  onFailure:  function(){
    alert('ERROR');
  }
});
:


IE将缓存URL以加快加载速度,但如果您(比如)每隔一段时间轮询服务器以获取新信息,IE将缓存该URL并可能返回您一直拥有的相同数据集

无论最终如何执行GET请求(香草JavaScript、Prototype、jQuery等),都要确保设置了一种机制来对抗缓存。为了解决这个问题,在你要点击的URL的末尾附加一个唯一的标记。这可以通过以下方式实现:

var sURL = '/your/url.html?' + (new Date()).getTime();

这将在URL的末尾附加一个唯一的时间戳,并防止任何缓存发生。

在您的小部件的Info.plist文件中,不要忘记将您的
AllowNetworkAccess
键设置为true。

最好的方法是使用AJAX(您可以在本页上找到一个简单的教程)。原因是您可能使用的任何其他技术都需要更多的代码,不能保证在不返工的情况下跨浏览器工作,并且需要您通过在框架内打开隐藏页面、传递URL解析其数据并关闭它们来使用更多的客户机内存。
在这种情况下,AJAX是一种可行的方法。这就是我两年来javascript的繁重开发

我不熟悉Mac OS Dashcode小部件,但如果它们允许您使用JavaScript库和支持,我会使用并执行以下操作:

var page_content;
$.get( "somepage.php", function(data){
    page_content = data;
});
      Property1: value
      Property2: value
      etc.

如果您希望使用仪表板小部件的代码,并且不希望在创建的每个小部件中都包含JavaScript库,那么可以使用Safari本机支持的对象XMLHttpRequest

正如Andrew Hedges所报道的,默认情况下,小部件无法访问网络;您需要在与小部件关联的info.plist中更改该设置。

浏览器(和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;
}
但是,不鼓励同步请求,并将生成以下警告:

注意:从Gecko 30.0(Firefox 30.0/Thunderbird 30.0/SeaMonkey 2.27)开始,由于对用户体验的负面影响,主线程上的同步请求已被弃用

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

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);
}

没有回调的版本

var i = document.createElement("img");
i.src = "/your/GET/url?params=here";

上面有很多很好的建议,但不是很好的重用,而且常常充满了DOM胡说八道和其他隐藏简单代码的漏洞

下面是我们创建的一个Javascript类,它是可重用且易于使用的。目前它只有一个GET方法,但这对我们来说是有效的。添加一个帖子不应该影响任何人的技能

var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() { 
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );            
        anHttpRequest.send( null );
    }
}
使用它非常简单,如下所示:

var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
    // do something with response
});
复制粘贴现代版(使用和):

复制粘贴经典版本:


您可以通过两种方式获取HTTP get请求:

  • 该方法基于xml格式。您必须传递请求的URL

    xmlhttp.open("GET","URL",true);
    xmlhttp.send();
    
  • 这是基于jQuery的。您必须指定要调用的URL和函数名

    $("btn").click(function() {
      $.ajax({url: "demo_test.txt", success: function_name(result) {
        $("#innerdiv").html(result);
      }});
    }); 
    
  • 对于那些使用它的人,它是
    $http.get

    $http.get('/someUrl').
      success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });
    
    对于post请求也可以执行相同的操作。
    看看这个链接吧

    新的API是使用ES6承诺的
    XMLHttpRequest
    的更干净的替代品。有一个很好的解释,但它归结为(从文章):

    目前在最新版本中表现良好(适用于Chrome、Firefox、Edge(v14)、Safari(v10.1)、Opera、Safari iOS(v10.3)、Android浏览器和Chrome for Android),但IE可能不会获得官方支持。可用,建议支持仍在大量使用的旧浏览器(2017年3月之前的Safari esp版本和同期的移动浏览器)

    我想这是否比jQuery或XMLHttpRequest更方便取决于项目的性质

    这里有一个到规范的链接

    编辑

    使用ES7 async/await,这变得简单(基于):


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

    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);
                }
            }
        };
    }
    
    也许有点过火了,但使用这段代码绝对安全

    用法:


    您也可以使用纯JS实现这一点:

    // Create the XHR object.
    function createCORSRequest(method, url) {
      var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
    } else {
    // CORS not supported.
    xhr = null;
    }
    return xhr;
    }
    
    // Make the actual CORS request.
    function makeCorsRequest() {
     // This is a sample server that supports CORS.
     var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';
    
    var xhr = createCORSRequest('GET', url);
    if (!xhr) {
    alert('CORS not supported');
    return;
    }
    
    // Response handlers.
    xhr.onload = function() {
    var text = xhr.responseText;
    alert('Response from CORS request to ' + url + ': ' + text);
    };
    
    xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
    };
    
    xhr.send();
    }
    

    请参阅:了解更多详细信息:

    简洁明了:

    consthttp=newxmlhttprequest()
    http.open(“GET”https://api.lyrics.ovh/v1/toto/africa")
    http.send()
    
    http.onload=()=>console.log(http.responseText)
    要刷新joann的最佳答案,请承诺这是我的代码:

    let httpRequestAsync = (method, url) => {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.onload = function () {
                if (xhr.status == 200) {
                    resolve(xhr.responseText);
                }
                else {
                    reject(new Error(xhr.responseText));
                }
            };
            xhr.send();
        });
    }
    

    为此,建议使用JavaScript承诺使用fetchapi。XMLHttpRequest(XHR)、IFrame对象或动态标记是较旧(且较笨重)的方法

    <script type=“text/javascript”> 
        // Create request object 
        var request = new Request('https://example.com/api/...', 
             { method: 'POST', 
               body: {'name': 'Klaus'}, 
               headers: new Headers({ 'Content-Type': 'application/json' }) 
             });
        // Now use it! 
    
       fetch(request) 
       .then(resp => { 
             // handle response }) 
       .catch(err => { 
             // handle errors 
        }); </script>
    
    
    //创建请求对象
    var请求=新请求('https://example.com/api/...', 
    {方法:'POST',
    正文:{'name':'Klaus'},
    标题:新标题({'Content-Type':'application/json'})
    });
    //现在使用它!
    提取(请求)
    .然后(resp=>{
    //句柄响应})
    .catch(错误=>{
    //处理错误
    }); 
    
    下面是一个非常好而且简单的异步请求:

    function get(url, callback) {
      var getRequest = new XMLHttpRequest();
    
      getRequest.open("get", url, true);
    
      getRequest.addEventListener("readystatechange", function() {
        if (getRequest.readyState === 4 && getRequest.status === 200) {
          callback(getRequest.responseText);
        }
      });
    
      getRequest.send();
    }
    

    这里是xml文件的另一种选择,可以将文件作为对象加载,并以非常快速的方式作为对象访问属性

    • 请注意,为了让javascript能够正确解释内容,有必要将文件保存为与HTML页面相同的格式。如果您使用UTF8,请使用UTF8等格式保存文件
    XML工作
    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();
    
    // Create the XHR object.
    function createCORSRequest(method, url) {
      var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
    } else {
    // CORS not supported.
    xhr = null;
    }
    return xhr;
    }
    
    // Make the actual CORS request.
    function makeCorsRequest() {
     // This is a sample server that supports CORS.
     var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';
    
    var xhr = createCORSRequest('GET', url);
    if (!xhr) {
    alert('CORS not supported');
    return;
    }
    
    // Response handlers.
    xhr.onload = function() {
    var text = xhr.responseText;
    alert('Response from CORS request to ' + url + ': ' + text);
    };
    
    xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
    };
    
    xhr.send();
    }
    
    let httpRequestAsync = (method, url) => {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.onload = function () {
                if (xhr.status == 200) {
                    resolve(xhr.responseText);
                }
                else {
                    reject(new Error(xhr.responseText));
                }
            };
            xhr.send();
        });
    }
    
    <script type=“text/javascript”> 
        // Create request object 
        var request = new Request('https://example.com/api/...', 
             { method: 'POST', 
               body: {'name': 'Klaus'}, 
               headers: new Headers({ 'Content-Type': 'application/json' }) 
             });
        // Now use it! 
    
       fetch(request) 
       .then(resp => { 
             // handle response }) 
       .catch(err => { 
             // handle errors 
        }); </script>
    
    function get(url, callback) {
      var getRequest = new XMLHttpRequest();
    
      getRequest.open("get", url, true);
    
      getRequest.addEventListener("readystatechange", function() {
        if (getRequest.readyState === 4 && getRequest.status === 200) {
          callback(getRequest.responseText);
        }
      });
    
      getRequest.send();
    }
    
         <property> value <property> 
    
          Property1: value
          Property2: value
          etc.
    
        var objectfile = {};
    
    function getfilecontent(url){
        var cli = new XMLHttpRequest();
    
        cli.onload = function(){
             if((this.status == 200 || this.status == 0) && this.responseText != null) {
            var r = this.responseText;
            var b=(r.indexOf('\n')?'\n':r.indexOf('\r')?'\r':'');
            if(b.length){
            if(b=='\n'){var j=r.toString().replace(/\r/gi,'');}else{var j=r.toString().replace(/\n/gi,'');}
            r=j.split(b);
            r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});
            r = r.map(f => f.trim());
            }
            if(r.length > 0){
                for(var i=0; i<r.length; i++){
                    var m = r[i].split(':');
                    if(m.length>1){
                            var mname = m[0];
                            var n = m.shift();
                            var ivalue = m.join(':');
                            objectfile[mname]=ivalue;
                    }
                }
            }
            }
        }
    cli.open("GET", url);
    cli.send();
    }
    
    getfilecontent('mesite.com/mefile.txt');
    
    window.onload = function(){
    
    if(objectfile !== null){
    alert (objectfile.property1.value);
    }
    }
    
    yournavigator.exe '' --allow-file-access-from-files
    
    // 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()
    
    <button type="button" onclick="loadXMLDoc()"> GET CONTENT</button>
    
     <script>
            function loadXMLDoc() {
                var xmlhttp = new XMLHttpRequest();
                var url = "<Enter URL>";``
                xmlhttp.onload = function () {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == "200") {
                        document.getElementById("demo").innerHTML = this.responseText;
                    }
                }
                xmlhttp.open("GET", url, true);
                xmlhttp.send();
            }
        </script>
    
    fetch('https://www.randomtext.me/api/lorem')