简体   繁体   中英

how i can convert this request call in javascript to ajax code

I have a request code in te javascript .. and i want to convert it to ajax call .. because i think that my code is very old ? can you help please ?

my function in the js is :

            function loadRest() {
    const request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (this.readyState === 4) {
            let result = parseResponse(this.status, this.responseText);
            if (result != null) {
                Rest.rests = result;
                createTable();
            }
        }
    };
    request.open("GET", Rest.baseURL + "/byCompany/" + logginedCompanyId, true);
    request.send();
} 


function parseResponse(status, responseText) {
    log(responseText);
    let responseObject = JSON.parse(responseText);
    if (status !== 200 || (responseObject.error && responseObject.error != null)) {
        alert("Error: " + responseObject.error);
        return null;
    }
    return responseObject.result;
}

you can use $.get() something like this

$.get('Rest.baseURL', function(response){

//

});

Here is what you wanted.

$('#ajax').click(function() { 
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "localhost:8080/restws/json/product/get",
        success: function(data){
            let result = JSON.parse(data);
            if(result != null) {
                Rest.rests = result;
                createTable();
            }
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM