如何用javascript组织http请求和响应?

如何用javascript组织http请求和响应?,javascript,Javascript,我正在使用一个greasemonkey脚本,它的函数是GM\u xmlhttpRequest,它与xmlhttpRequest类似,但允许跨站点脚本编写等 我对不同的页面做了一系列并行http请求,然后使用onload从这些页面读取一些数据。根据结果,我创建了新的http请求。这里是一个例子,代码可能不起作用,它更多地说明了我正在使用的东西 function calleniro(nicerows, attempt){ if( attempt === 1){ var who

我正在使用一个greasemonkey脚本,它的函数是
GM\u xmlhttpRequest
,它与
xmlhttpRequest
类似,但允许跨站点脚本编写等

我对不同的页面做了一系列并行http请求,然后使用onload从这些页面读取一些数据。根据结果,我创建了新的http请求。这里是一个例子,代码可能不起作用,它更多地说明了我正在使用的东西

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玩偶hydra,具有不断分支的onload函数。很难追踪到底发生了什么。我想将这些功能更多地分离为以下内容,例如:

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

我相信,你所寻找的或多或少都是在基本知识中捕捉到的。以最基本的形式,你可以做到:

function calleniro(foo,bar)
{
    this.tel = foo+"-"+bar;
}
contact = new calleniro("555","7777");
if (contact.tel)
...
但是由于执行ajax查询,您会遇到一些范围界定问题,因为
当您在
GM\u xmlhttpRequest
中时,此
具有不同的含义。但你可以用闭包来解决这个问题。下面是一个$.ajax示例,它将
this
作为
obj
传递到$.ajax函数中,因此我们使用
obj.tel
,而不是使用
this.tel
,从而避免了范围问题

(function(obj) {
    $.ajax({
        async: false,
        url: url,
        method: "GET",
        success: function(data) {
            obj.tel = data;
        }
    });
})(this);

让我知道这是否有意义,或者如果您有任何问题:)

这太棒了!我以前没有真正使用过面向对象的javascript。*现在开始阅读。*如何构造类等。我目前的想法是为每种类型的http请求创建一个类。并为每个http请求创建一个新对象。另一个问题是,$.ajax无法跨站点工作。