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

时间:2010-07-15 16:49:57

标签: javascript ajax greasemonkey synchronous gm-xmlhttprequest

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

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应该可以在整个脚本中重复使用,这些功能中的每一个都可以在脚本的不同部分单独使用或一起使用。

3 个答案:

答案 0 :(得分:3)

您是否有任何理由需要使用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);

其余我认为你可以弄清楚自己,祝你好运。

答案 1 :(得分:1)

通常你会把调用放在xmlhttprequest的响应处理程序中,这样它就会立即返回,当它确实得到那个页面时,就会执行所需的代码。

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

答案 2 :(得分:0)

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

尚未测试过,但您明白了