【问题标题】:JSONP response failing to be stored in a closureJSONP 响应未能存储在闭包中
【发布时间】:2018-03-05 18:37:53
【问题描述】:

我通过 JSONP 发出 API 请求以避免跨域错误。我想将响应存储在闭包(函数表达式“模块”)中的变量中,该变量可通过两个“公共方法”访问。

其中一个方法 module.store 是 API 响应使用的回调。另一种方法使用 API 响应的内容更新 p 标签。

点击“提交”发起API请求后,我知道回调成功调用了,因为我可以在它消失之前短暂看到更新的显示。

我想一旦函数退出我肯定会丢失响应,但闭包应该仍然能够访问私有变量。

如果我从浏览器中调用 requestJSONP(),它就可以工作。

我无法在 JS fiddle 中重新创建问题,因为它不喜欢 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;

}     

【问题讨论】:

  • jsonp 从全新/全局上下文中调用,不涉及闭包...

标签: javascript ajax closures jsonp


【解决方案1】:

默认行为(至少在 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");
};  

【讨论】:

    猜你喜欢
    • 2012-02-09
    • 2014-12-27
    • 2012-08-18
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 2012-07-29
    • 1970-01-01
    相关资源
    最近更新 更多