2017-09-24 29 views
0

我正在通過JSONP發出API請求以避免跨域錯誤。我想將響應存儲在一個閉包(一個函數表達式「module」)中的變量中,該變量通過兩個「公共方法」訪問。JSONP響應無法存儲在關閉中

其中一個方法module.store是API響應使用的回調函數。另一種方法用API響應的內容更新p標籤。

當我點擊「提交」以啓動API請求後,我知道回調已成功調用,因爲我可以在消失之前簡要地看到更新後的顯示。

我想我必須丟失響應,一旦函數退出,但閉包應該仍然能夠訪問私有變量。

如果我從瀏覽器中調用requestJSONP(),它將起作用。

我無法在JS小提琴中重新創建問題,因爲它不喜歡JSONP請求。

HTML:

<body> 
<header>Wikipedia Viewer</header> 
<section> 
    <div class="container"> 
     <p>default text</p> 
     <form> 
      <button>Submit</button> 
     </form> 
    </div> 
</section> 
</body> 

JS:

document.addEventListener('DOMContentLoaded', addListenerToButton); 

//callback for DOM load which adds a click event on the submit button 
function addListenerToButton() { 

var button = document.getElementsByTagName("button")[0]; 

button.addEventListener("click", requestJSONP); 
console.log("addListenerToButton"); 
}; 

//advoids cross browser origin error 
function requestJSONP(searchTerm) { 
    //dynamically create a script tag 
    var scriptTag = document.createElement("script"); 
    //set url 
    scriptTag.src = "https://en.wikipedia.org/w/api.php?action=opensearch&search=covfefe&limit=10&namespace=0&format=json&callback=test"; 
    //append tag to head element 
    document.getElementsByTagName("head")[0].appendChild(scriptTag); 
    console.log("got to JSONP"); 
}; 

function test(data){ 
     module.store(data); 
} 

//callback invoked when API sends reponse 
var module = (function(){ 
    var storedValue = []; 
console.log("got to module"); 
    return { 
     store: function(val){ 
      storedValue.push(val); 
      console.log("got to module.store"); 
      displayArray(); 
     }, 

     retrieve: function(){ 
      return storedValue; 
     }, 

    } 

}()); 

function displayArray(){ 
    var stored = module.retrieve(); 
    pTag = document.getElementsByTagName("p")[0]; 
    text = pTag.textContent = stored; 

}  
+1

jsonp從新/全局上下文調用,沒有關閉涉及... – dandavis

回答

0

默認行爲(在Chrome中至少)是刷新頁面,這是清除存儲的值。我已覆蓋下面的默認行爲:

function saveText(event) { 
    debugger 
    event.preventDefault() 
    var userInput = document.getElementsByTagName("input")[0].value; 

    if (userInput === "") { 
     alert("Please enter a search term") 
     return 
    } 
    requestJSONP(userInput); 
    console.log("saveText"); 
};