gpt4 book ai didi

javascript - 具有多个闭包的嵌套 XMLHttpRequests 是个好主意吗?

转载 作者:行者123 更新时间:2023-11-30 09:09:17 24 4
gpt4 key购买 nike

我有一个 Greasemonkey 脚本,它在视频网站的搜索结果页面上运行。该脚本的功能是获取一个使用 Flash 播放器打开新窗口的 javascript 链接,跳过一些重定向环,然后插入一个指向所需 FLV 文件的常规链接。

我已经更改了脚本来做一些愚蠢但在结构上与 en.wikipedia.org 相同的事情。我的问题是 3 个嵌套闭包和嵌套 xmlhttprequests 是否是解决此问题的最佳方法。


// ==UserScript==
// @name wiki mod example
// @namespace http://
// @description example script
// @include *wikipedia.org*
// ==/UserScript==

var candidates = document.getElementsByTagName("a");

for (var cand = null, i = 0; (cand = candidates[i]); i++) {
if (cand.href.match(/\/wiki\/W/)) { // for all articles starting with 'W'
var progress = document.createElement('span');
progress.appendChild(document.createTextNode(" Start"));
cand.parentNode.insertBefore(progress, cand.nextSibling);
progress.addEventListener("click",
function(link1) { return function() { // link1 is cand.href
this.innerHTML = " finding...";

GM_xmlhttpRequest({method:"GET",url:link1,
onload:function(p) { return function(responseDetails) {
// p is is the current progress element
// the first linked article starting with 'S' is *special*
var link2 = responseDetails.responseText.match(/\/wiki\/S[^"]+/);
if(!link2) { p.innerHTML = "failed in request 1"; return;}

GM_xmlhttpRequest({method:"GET",url:"http://en.wikipedia.org"+link2[0],
onload:function(p2) { return function(responseDetails) {
// p2 is p, ie. progress
// link3 would contain the URL to the FLV in the real script
var link3 = responseDetails.responseHeaders.match(/Content-Length.+/);
if(!link3) { p2.innerHTML = "failed in request 2"; return;}

var elmNewContent = document.createElement('p');
elmNewContent.appendChild(document.createTextNode(link3));
p2.parentNode.insertBefore(elmNewContent, p2.nextSibling);
p2.innerHTML = " <em>Done</em>";
}}(p) // 3rd closure
}); // end of second xmlhttprequest

}}(this) // 2nd closure
}); // end of first xmlhttprequest

}}(cand.href), true); // 1st closure and end of addeventlistener
}
}

最佳答案

好吧,您可以通过为每个阶段创建单独的函数,然后让阶段 1 调用阶段 2 等来提高可读性。所以,而不是

request({onload: function(response) {
request({onload: function(response) {
request({onload: function(response) {
alert("psych!");
}});
}});
}});

你会

request({onload: doTheNextThing});

function doTheNextThing(responseObject) {
request({onload: doTheRightThing});
}

function doTheRightThing(responseObject) {
request({onload: doTheLastThing});
}

function doTheLastThing(responseObject) {
alert("psych!");
}

关于javascript - 具有多个闭包的嵌套 XMLHttpRequests 是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1750970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com