2016-10-27 6 views
3

私の質問を読んでくれてありがとう!JSONPリクエストからの応答をバニラのJavaScriptで保存する

JSONPリクエストからの応答を、同じサーバーに別の要求を行った後で後でアクセスできる新しいオブジェクトに格納しようとしています。この目的は、ユーザーが以前の要求からデータをスクロールできるようにすることです。

これは私のコードです:

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; 
} 

私はdisplayDataオブジェクトがグローバル変数に代入する必要があることを信じています。私はそれをするためにさまざまな方法を試してきたし、それを機能させるように見えない。助けてください。

+0

あなたの質問にソースを含めてください。オフサイトのリソースへのリンクは腐敗する傾向があります。 – Tibrogargan

+0

@Tibrogargan私はあなたが「ソース」という意味を理解しているかどうかはわかりません。 apiへのソースURL? –

+0

あなたはそれをIMOに含めました。彼はおそらくすでにそこにあるソースコードを意味するでしょう.... – Feathercrown

答えて

3
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; 
} 

これまでのすべての回答が含まれています。

+0

を作成するだけで済むと思います。 jsonpData [0] .quoteText;でオブジェクトのプロパティの値にアクセスできるようになりました。ありがとうございました! –

+0

...しかし、あなたが応答を受け取ったときには、決して知らないことです。あなたが探しているときに配列がまだ空であるかもしれません。 – Bergi

1

約束使用する:あなたはこのようにそれを使用することができます

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); 
}); 

を:あなたはいつでも

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

ただ、datathenをチェーン - データがまだない場合は、コールバックが待っていますロードされる。

関連する問題