Search code examples
javascriptjsonajaxxmlhttprequest

How to get a JSON from an URL


I have this code:

function getJSON(url) {
    var resp ;
    var xmlHttp ;

    resp  = '' ;
    xmlHttp = new XMLHttpRequest();

    if(xmlHttp != null)
    {
        xmlHttp.open( "GET", url, false );
        xmlHttp.send( null );
        resp = xmlHttp.responseText;
    }

    return resp ;
}

var data ;
data = getJSON('https://gpsfront.aliexpress.com/getRecommendingResults.do?offset=1&postback=8fa025df-0612-4a7f-9901-5820a67473e1&widgetId=7237617') ;

alert(data);
alert("");

When I get the JSON using an URL like this, then everything works and the JSON is displayed in the alert. However, when the URL is this, then the script does not work. The JSON is given in asynchronous code and it's valid, so what can be the reason?

I have another question. How can I scrape the HTML of a page and place it in a variable using pure javascript?


Solution

  • First, you should consider using the fetch interface and the async/await keywords.

    You could write it like this. As for your links, I'm getting a CORS problem. Are you sure you are using the right API?

    const getJson = async(p_url)=>{
        const params = {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            }
        };
        const req = await fetch(
            p_url,
            params
        );
        if(req.ok){
            const rep =await req.json();
            return rep;
        }
    }

    as for getting the whole HTML of a page you simply have to use the DOM

    const page = document.documentElement.innerHTML;
    console.log(page);