如何在javascript中组织带有响应的http请求?

时间:2013-08-05 23:08:44

标签: javascript

我正在使用一个带有函数GM_xmlhttpRequest的greasemonkey脚本,它与xmlhttpRequest类似,但允许跨站点脚本等。

我正在对各种页面进行一系列的paralel http请求,然后使用onload从这些页面中读取一些数据。根据结果​​,我制作了新的http-requst。这是一个例子,代码可能不起作用,它更多的是说明我正在使用的东西。

function calleniro(nicerows, attempt){
    if( attempt === 1){
        var who = nicerows.contact.firstname+' '+nicerows.contact.lastname;
        var where = ''
    }else if(attempt === 2){
        var who = nicerows.contact.firstname+' '+nicerows.contact.lastname;
        var where = nicerows.contact.postal;
    }else if(attempt === 3){
        var who = nicerows.contact.firstname+' '+nicerows.contact.lastname;
        var where = nicerows.contact.adress;
    }

    var url = 'http://personer.eniro.se/resultat/'+who+'/'+where;
    GM_xmlhttpRequest({
    method: "GET",
    url: url,
    onload: function(data) {
        data = $.parseHTML(data.response);
        var phone = $(data).find('.tel.row a').map(function(){
            return $(this).text();
        }).get();
        //one company, save the data
        if(vCard.length = 1){
            //adding the company if we find a phonenumber or more.
            if (phone.length > 0){ 
                nicerows.contact.phone = phone;
            }
        more than one company.
        }else if(vCard > 1){
            attempt++;
            calleniro(nicerows, attempt)
        }


    }
})
}

这非常快速地转向了一个带有分支上载功能的bubushka doll-hydra。跟踪发生的事情非常困难。我想将函数更多地分成这样的东西,例如:

var contact = callenrio(foo,bar)
//the next thing should happen after onload only.
if(contact.tel){ 
save(contact);
}
else{
callenrio(foobar,barfoo)
}

1 个答案:

答案 0 :(得分:1)

我相信您所寻找的内容或多或少都会在Object-Oriented Javascript的基础知识中被捕获。在这是你可以做的最基本的形式:

function calleniro(foo,bar)
{
    this.tel = foo+"-"+bar;
}
contact = new calleniro("555","7777");
if (contact.tel)
...

但是,由于您正在执行ajax查询,因此遇到了一些范围问题,因为当您在this内时GM_xmlhttpRequest具有不同的含义。但是你可以用一个闭包修复它。以下是$ .ajax示例,它将this作为obj传递到$ .ajax函数中,因此我们使用this.tel而不是obj.tel,而是避免使用(function(obj) { $.ajax({ async: false, url: url, method: "GET", success: function(data) { obj.tel = data; } }); })(this); 范围问题..

{{1}}

如果这有意义或者您有任何疑问,请告诉我们。)