user6275623
user6275623

Reputation:

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.

Upvotes: 3

Views: 397

Answers (2)

Bergi
Bergi

Reputation: 664620

Use a promise:

var data = new Promise(function getData(resolve, reject) {
    window.setData = resolve;
    var script = document.createElement("script");
    script.src = "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=setData";
    script.onerror = reject;
    document.getElementsByTagName("head")[0].appendChild(script);
});

You can use it like this:

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

Just chain a then onto data, whenever you want - the callback will wait if the data is not yet loaded.

Upvotes: 0

Adrian Brand
Adrian Brand

Reputation: 21638

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.

Upvotes: 2

Related Questions