繁体   English   中英

如何在greasemonkey中进行同步AJAX调用?

[英]How to make synchronous AJAX calls in greasemonkey?

我有一个URL列表,需要一个接一个地加载每个页面。
这是我心中的主要功能。

mainFunction() {  
loop {  // Loop through URL list
oPage = func1(URL); //Get page contents
aResult = func2(oPage); //Analyse the contents
func3(aResult); //Do current page modifications
}  
}

func1使用GM_xmlhttprequest,它是异步的,因此oPage导致'underfined'作为函数结束,然后才能检索页面的内容。
func2也使用GM_xmlhttprequest,所以即使oPage未定义,aResult也将是未定义的。

关于如何使所有这些工作的任何想法?

func1 func2func3应该可以在整个脚本中重复使用,这些函数中的每一个都可以在脚本的不同部分中单独使用或一起使用。

您有什么理由需要使用Greasemonkey特定功能吗? 您是在进行跨站点请求还是特别需要它的东西? 查看Greasemonkey的Wiki ,我找不到将asynchronous设置为false的选项。

最简单的选择是将JQuery包含在Greasemonkey脚本中并使用JQuerys AJAX功能。 当然,这可以在没有JQuery的情况下完成,但是,在这个领域中跨浏览器不兼容是手动处理的痛苦。

使用JQuery,您的代码看起来像这样:

function func1(url) {
    var result;

    $.ajax({
        type: "GET",
        url: url,
        async: false,
        success: function(data){
            result = data;
        }
    });
    return result;
}

你会像这样声明你的变量oPage

var oPage = func1(url);

剩下的我觉得你可以搞清楚自己,祝你好运。

通常,您会将调用放在xmlhttprequest的响应处理程序中,以便它立即返回,当它确实获取该页面时,它会执行所需的代码。

如果你真的需要按特定的顺序让它们发生,你可以在第二次拨打第一个电话时返回,等等。

var urls = [];

(function recursive(list)
{
    if (list[0])    // the list is not empty
    GM_xmlhttpRequest({ // that would be "func1"
        "url" : list[0],    // first url in the list
        "onload" : function(xhr)
        {
            var oPage = xhr.responseText,   // page contents
            aResult = func2(oPage); // analyse the contents
            func3(aResult); // do current page modifications

            list.shift();   // remove the first link of the list
            recursive(list);    // go to the next url in the list
        }
    });
    else
    alert("end of list");
})(urls);

没有测试过,但你明白了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM