How to get the response of XMLHttpRequest?

后端 未结 4 1622
挽巷
挽巷 2020-11-22 06:23

I\'d like to know how to use XMLHttpRequest to load the content of a remote URL and have the HTML of the accessed site stored in a JS variable.

Say, if I wanted to l

4条回答
  •  情深已故
    2020-11-22 07:19

    The simple way to use XMLHttpRequest with pure JavaScript. You can set custom header but it's optional used based on requirement.

    1. Using POST Method:

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

    You can send params using POST method.

    2. Using GET Method:

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

提交回复
热议问题