문제

나는해야한다 http를 얻습니다 JavaScript로 요청하십시오. 그렇게하는 가장 좋은 방법은 무엇입니까?

Mac OS X 대시 코드 위젯 에서이 작업을 수행해야합니다.

도움이 되었습니까?

해결책

브라우저 (및 대시 코드)는 JavaScript에서 HTTP 요청을하는 데 사용할 수있는 XMLHTTPREQUEST 객체를 제공합니다.

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

다른 팁

jQuery에서:

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);

위의 많은 훌륭한 조언이 많지만 재사용 할 수는 없으며 Dom Nonsense 및 쉬운 코드를 숨기는 다른 보풀로 가득 차 있습니다.

재사용 가능하고 사용하기 쉬운 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
});

콜백이없는 버전

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

새로운 window.fetch API는 더 깨끗한 대체품입니다 XMLHttpRequest 그것은 ES6 약속을 사용합니다. 좋은 설명이 있습니다 여기, 그러나 그것은 (기사에서)로 귀결됩니다.

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function() {
  console.log("Booo");
});

브라우저 지원 이제 최신 릴리스 (Chrome, Firefox, Edge (v14), Safari (v10.1), Opera, Safari IOS (v10.3), Android 브라우저 및 Android 용 Chrome에서 작동하는 경우가 이제는 그렇지 않을 것입니다. 공식 지원을 받으십시오. Github에는 Polyfill이 있습니다 오래된 브라우저를 여전히 사용하는 것이 좋습니다 (2017 년 3 월 Safari의 ESP 버전 및 같은 기간의 모바일 브라우저).

이것이 jQuery 또는 XMLHTTPREQUEST보다 더 편리한 지 여부는 프로젝트의 특성에 따라 다릅니다.

다음은 사양에 대한 링크입니다 https://fetch.spec.whatwg.org/

편집하다:

ES7 ASYNC/AWAIT를 사용하면 간단하게됩니다 ( 이 요점):

async function fetchAsync (url) {
  let response = await fetch(url);
  let data = await response.json();
  return data;
}

다음은 JavaScript와 직접 수행하는 코드입니다. 그러나 앞에서 언급했듯이 JavaScript 라이브러리를 사용하면 훨씬 나을 것입니다. 내가 가장 좋아하는 것은 jQuery입니다.

아래의 경우, JavaScript JSON 객체를 반환하기 위해 ASPX 페이지 (가난한 사람의 휴식 서비스로 서비스하는)가 호출됩니다.

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

사본-페이스트 준비 버전

let request = new XMLHttpRequest();
request.onreadystatechange = function () {
    if (this.readyState === 4) {
        if (this.status === 200) {
            document.body.className = 'ok';
            console.log(this.responseText);
        } else if (this.response == null && this.status === 0) {
            document.body.className = 'error offline';
            console.log("The computer appears to be offline.");
        } else {
            document.body.className = 'error';
        }
    }
};
request.open("GET", url, true);
request.send(null);

즉, 더 빠르게로드하기 위해 URL을 캐시하지만, 예를 들어, 새로운 정보를 얻으려고 노력하는 간격으로 서버를 폴링하는 경우, 즉 URL을 캐시하고 항상 가지고있는 동일한 데이터 세트를 반환 할 것입니다.

GET 요청을 수행하는 방법에 관계없이 바닐라 JavaScript, 프로토 타입, jQuery 등 - 캐싱 전투를위한 메커니즘을 마련해야합니다. 이를 퇴치하려면 URL의 끝까지 독특한 토큰을 추가하십시오. 이것은 다음과 같이 할 수 있습니다.

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

이렇게하면 URL 끝에 고유 한 타임 스탬프가 추가되며 캐싱이 발생하지 않도록합니다.

짧고 순수한 :

const http = new XMLHttpRequest()

http.open("GET", "https://api.lyrics.ovh/v1/toto/africa")
http.send()

http.onload = () => console.log(http.responseText)

원기 죽은 것을 단순하게 만듭니다

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

Mac OS 대시 코드 위젯에 익숙하지는 않지만 JavaScript 라이브러리와 지원을 사용할 수 있으면 xmlhttprequests, 나는 사용할 것이다 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();

위젯의 info.plist 파일에서 설정하는 것을 잊지 마십시오 AllowNetworkAccess 진실의 열쇠.

가장 좋은 방법은 Ajax를 사용하는 것입니다 (이 페이지에서 간단한 자습서를 찾을 수 있습니다. Tizag). 그 이유는 당신이 사용할 수있는 다른 기술에 더 많은 코드가 필요하기 때문입니다. 재 작업없이 크로스 브라우저를 작동시키는 것이 보장되지 않으며, 데이터를 구문 분석하고 닫는 URL을 전달하는 프레임 내부에 숨겨진 페이지를 열어 더 많은 클라이언트 메모리를 사용해야합니다. Ajax는이 상황에서가는 길입니다. 2 년간의 JavaScript 무거운 개발 말.

사용하는 사람들을 위해 Angularjs, 그것의 $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.
  });

두 가지 방법으로 HTTP GET 요청을받을 수 있습니다.

  1. 이 접근법은 XML 형식을 기반으로합니다. 요청에 대해 URL을 전달해야합니다.

    xmlhttp.open("GET","URL",true);
    xmlhttp.send();
    
  2. 이것은 jQuery를 기반으로합니다. 호출하려는 URL과 function_name을 지정해야합니다.

    $("btn").click(function() {
      $.ajax({url: "demo_test.txt", success: function_name(result) {
        $("#innerdiv").html(result);
      }});
    }); 
    
function get(path) {
    var form = document.createElement("form");
    form.setAttribute("method", "get");
    form.setAttribute("action", path);
    document.body.appendChild(form);
    form.submit();
}


get('/my/url/')

사후 요청에 대해서도 동일한 작업을 수행 할 수 있습니다.
이 링크를 살펴보십시오 양식 제출과 같은 JavaScript 게시물 요청

이 Fetch API를 수행하는 것은 JavaScript 약속을 사용하여 권장되는 접근법입니다. XMLHTTPREQUEST (XHR), iframe 객체 또는 동적 태그는 이전 (및 Clunkier) 접근 방식입니다.

<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>

여기에 위대한 것입니다 데모를 가져 오십시오 그리고 MDN 문서

간단한 비동기 요청 :

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

Ajax

당신은 다음과 같은 라이브러리를 사용하는 것이 가장 좋습니다 원기 또는 jQuery.

대시 보드 위젯에 코드를 사용하려면 생성 한 모든 위젯에 JavaScript 라이브러리를 포함시키지 않으려면 Safari가 기본적으로 지원하는 XMLHTTPREQUEST를 사용할 수 있습니다.

Andrew Hedges 가보고 한 바와 같이 위젯은 기본적으로 네트워크에 액세스 할 수 없습니다. 위젯과 관련된 info.plist에서 해당 설정을 변경해야합니다.

약속으로 Joann의 Best Answer를 새로 고치기 위해 이것은 내 코드입니다.

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

순수한 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();
}

자세한 내용은 참조 : html5rocks 튜토리얼

다음은 파일을 객체로로드하고 매우 빠른 방식으로 객체로서 액세스 속성에 대한 XML 파일의 대안입니다.

  • 주의, JavaScript가 그를 할 수 있고 콘텐츠를 올바르게 해석하려면 파일을 HTML 페이지와 동일한 형식으로 저장해야합니다. UTF 8을 사용하는 경우 UTF8에 파일을 저장하십시오.

XML은 나무로 작동합니다. 글쓰기 대신

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

그룹에 출연하는 것은 작은 선물 일뿐입니다. 당신과 같은 감사합니다 :)

PC의 기능을 로컬로 테스트하려면 다음 명령 (Safari를 제외한 모든 브라우저에서 지원)으로 브라우저를 다시 시작하십시오.

yournavigator.exe '' --allow-file-access-from-files
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top