Search code examples
javascriptjsonp

Storing responses from JSONP request with vanilla JavaScript


Thanks for taking the time to read my question!

I am trying to store the response from a JSONP request into a new object which value I can later access after making another request to the same server. The purpose of this is to allow the user to scroll through the data from previous requests.

This is my code:

window.onload = getData;
function getData() {
    var script = document.createElement("script");
    script.src = "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=displayData";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function displayData(response) {
    document.getElementById("quote").innerHTML = response.quoteText;
    document.getElementById("cite").innerHTML = response.quoteAuthor;
}

I believe that displayData object needs to be assigned to a global variable. I have tried different ways to do that and can't seem to make it work. Please help.


Solution

  • window.onload = getData;
    function getData() {
        var script = document.createElement("script");
        script.src = "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=displayData";
        document.getElementsByTagName("head")[0].appendChild(script);
    }
    
    var previousResponses = [];
    
    function displayData(response) {
        previousResponses.push(response);
        document.getElementById("quote").innerHTML = response.quoteText;
        document.getElementById("cite").innerHTML = response.quoteAuthor;
    }
    

    Now you have an arrary that contains all the previous responses.