development

XMLHttpRequest의 응답을 얻는 방법?

big-blog 2020. 5. 28. 19:11
반응형

XMLHttpRequest의 응답을 얻는 방법?


XMLHttpRequest를 사용하여 원격 URL의 내용을로드하고 액세스하는 사이트의 HTML을 JS 변수에 저장하는 방법을 알고 싶습니다.

http://foo.com/bar.php 의 HTML을로드하고 alert ()하려면 어떻게해야합니까?


다음과 같은 방법으로 그것을 얻을 수 XMLHttpRequest.responseText있는 XMLHttpRequest.onreadystatechange경우 XMLHttpRequest.readyState에 같습니다 XMLHttpRequest.DONE.

다음은 예제입니다 (IE6 / 7과 호환되지 않음).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

IE6 / 7뿐만 아니라 일부 브라우저 특정 메모리 누수 또는 버그를 해결하고 아약스 요청을 발생시킬 때의 자세한 표시를 위해 브라우저 간 호환성 향상을 위해 jQuery를 사용할 수 있습니다 .

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

당신이 취할했습니다합니다 자바 스크립트에 대한 동일 출처 정책을 로컬 호스트에서 실행하지 않을 경우 계정으로. 도메인에서 프록시 스크립트를 작성하는 것이 좋습니다.


에서 살펴볼 것을 제안 fetch합니다. ES5와 동일하며 약속을 사용합니다. 훨씬 더 읽기 쉽고 쉽게 사용자 정의 할 수 있습니다.

const url = "https://stackoverflow.com";
fetch(url)
    .then(
        response => response.text() // .json(), etc.
        // same as function(response) {return response.text();}
    ).then(
        html => console.log(html)
    );

Node.js에서 다음을 fetch사용하여 가져와야합니다 .

const fetch = require("node-fetch");

동 기적으로 사용하려는 경우 (상위 범위에서는 작동하지 않음) :

const json = await fetch(url)
  .then(response => response.json())
  .catch((e) => {});

더 많은 정보:

모질라 문서

사용할 수 있습니까 (2019 년 10 월 94 %)

매트 월시 튜토리얼


XMLHttpRequest와 함께 사용하는 간단한 방법 pure JavaScript. 설정할 수 custom header있지만 요구 사항에 따라 선택적으로 사용됩니다.

1. POST 방법 사용 :

window.onload = function(){
    var request = new XMLHttpRequest();
    var params = "UID=CORS&name=CORS";

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };

    request.open('POST', 'https://www.example.com/api/createUser', true);
    request.setRequestHeader('api-key', 'your-api-key');
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send(params);
}

POST 메소드를 사용하여 매개 변수를 보낼 수 있습니다.

2. GET 방법 사용 :

Please run below example and will get an JSON response.

window.onload = function(){
    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };

    request.open('GET', 'https://jsonplaceholder.typicode.com/users/1');
    request.send();
}


In XMLHttpRequest, using XMLHttpRequest.responseText may raise the exception like below

 Failed to read the \'responseText\' property from \'XMLHttpRequest\': 
 The value is only accessible if the object\'s \'responseType\' is \'\' 
 or \'text\' (was \'arraybuffer\')

Best way to access the response from XHR as follows

function readBody(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    }
    return data;
}

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(readBody(xhr));
    }
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);

참고URL : https://stackoverflow.com/questions/3038901/how-to-get-the-response-of-xmlhttprequest

반응형