>  기사  >  웹 프론트엔드  >  AJAX를 구현하는 네이티브 자바스크립트의 코드 예

AJAX를 구현하는 네이티브 자바스크립트의 코드 예

不言
不言앞으로
2018-10-27 15:11:182278검색

이 기사의 내용은 기본 JavaScript로 AJAX를 구현하기 위한 코드 예제입니다. 필요한 친구가 참고할 수 있기를 바랍니다.

Native JS는 AJAX 코드를 사용하며 코드는 다음과 같습니다

var xhr1 = new XMLHttpRequest;
        xhr1.open("POST", 'http://47.92.121.171:17788', true);
        xhr1.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr1.onreadystatechange = function () {
            if (xhr1.readyState == 4 && xhr1.status == 200) {
                console.log("打印用户信息1" + xhr1.responseText);
            }
        }

        xhr1.send("code=p_001&name=aaaaaa&pas=123456&belong=aabbccdd");

Ajax 실행 메소드가 완료된 후 결과를 호출해야 하는 경우 콜백 함수나 promise를 사용해야 합니다

콜백 함수

     private loadXMLDoc(url, sendcode, cfunc) {
        this.xmlhttp = new XMLHttpRequest;
        this.xmlhttp.open("POST", url, true);
        this.xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        this.xmlhttp.onreadystatechange = cfunc;
        this.xmlhttp.send(sendcode);
    }
    private myFunction() {
        this.loadXMLDoc("http://47.92.121.171:17788", "code=p_001&name=aaaaaa&pas=123456&belong=aabbccdd",()=>{
            if (this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) {
                console.log("3")
                console.log("打印用户信息1" + this.xmlhttp.responseText) 
            }
        });
    }

promise 사용

this.getGameServer().then(function (res) {
            console.log("res" + res);
        }).catch(function (rej) {
            console.log("rej" + rej);
        });private getGameServer() {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest;
            xhr.open("POST", 'http://47.92.121.171:9002/rout/get_game_servers', true);
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {        
                if (xhr.readyState == 4 && xhr.status == 200) {
                    resolve(xhr.responseText);
                }
            }
            xhr.send("game=1&shang=common");
        });
    }

위 내용은 AJAX를 구현하는 네이티브 자바스크립트의 코드 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 csdn.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제