2012-12-06 138 views
0

我可以在浏览器中传递重定向url和用户id的参数,这是一个intranet应用程序btw。因此,您可以粘贴地址,例如“http:// intranetapp?redirect_url = http:// crapola & userid = xxxxxxx。它将您重定向到该网址并提供用户ID的其他信息,这是我想要获取的有几百个用户,这些信息作为你重定向的参数的一部分被返回,有没有办法用jQuery或jQuery的相关方法调用(GET请求),读取返回的url和参数,而不是仅仅获取返回的html?使用jquery ajax从重定向请求中读取url参数

+0

如果它们作为HTTP标头的一部分返回,[this](http://stackoverflow.com/questions/6696229/jquery-ajax-fetch-only-headers-and-decide-wether-to-get-内容)可能会有所帮助。 – ebrandell

+0

我不知道我的理解,但也许这会有所帮助。当前页面的查询字符串('''右侧的所有内容)可作为'location.search'提供给javascript,它可以被解析出来以确定每个参数的名称|值。 –

回答

1

克里斯,如果我理解正确的话,你想要做的是适度棘手。

我从来没有需要做这种事情,但原则上知道它涉及一种不寻常的ajax请求类型 - 即“HEAD”请求,允许检查重定向url(和其他元数据)而不接收HTTP响应的主要部分(正文)。

您的Intranet服务器应该处理HEAD请求(它们至少与GET一样安全),但不一定。如果没有,那么请与你的服务器管理员说一句话。如果你是服务器管理员,那么在httpd.conf文件和/或相应的.htaccess文件(假设为Apache)中有一个根。

与所有类型的ajax一样,代码也很棘手,因为它的一部分需要异步运行(当服务器的HTTP响应返回时)。为了解决这个问题,jQuery的Deferreds/Promises可以(宽松地)使用。

你的主要工作器功能(仍然如果我理解正确的)会是这样的:

function getUserParams(userID) { 
    var $ = jQuery, 
     dfrd = $.Deferred(), 
     q = {}, 
     baseURL = 'http://intranetapp?redirect_url=http://crapola&userid='; 
    $.ajax({ 
     type: "HEAD", 
     url: baseURL + userID, 
     cache: false, 
     success: function(data, textStatus, jqXHR) { 
      var location = jqXHR.getResponseHeader('Location'); 
      if(location){ 
       var search = $("<a>").attr('href', location).get(0).search.replace(/^[?]/, ''), 
        prop, pair; 
       if (search) { 
        $.each(search.split("&"), function(i, arg) { 
         pair = arg.split("="); 
         if (pair.length >= 1) { 
          prop = pair.shift(); 
          q[prop] = (pair.length == 1) ? pair[0] : (pair.length > 1) ? pair.join('=') : ''; 
         } 
        }); 
       } 
       //At this point q is a hash representing parameters in the location's search string. 
       dfrd.resolve(userID, q); 
      } 
      else { 
       dfrd.reject(userID, 'No redirect url in the response'); 
      } 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
      dfrd.reject(userID, 'Ajax failure: ' + textStatus + ': ' + errorThrown); 
     } 
    }); 
    return dfrd.promise(); 
} 

需要注意的是,由于AJAX是异步的,我们回到一个承诺不是我们真正想要的结果;他们稍后到达,打包在javascript普通对象q中。

下面是如何测试getUserParams()

var userID = '12345678'; 
getUserParams(userID).done(function(userID, q) { 
    //Work with userID and q as required 
    console.log(['Success', userID, q.fullname, q.status, q.postalcode].join(': '));//for example 
}).fail(function(userID, message) { 
    //Handle error case here 
    message = message || ''; 
    console.log(['Error', userID, message].join(': '));//for example 
}); 

你的使用目的,与数百名的URL,将是这样的:

var userIDs = [ 
    //array of userIDs (hard coded or otherwise constructed) 
    '1234', 
    '5678' 
]; 
var promises = []; 
$.each(userIDs, function(i, userID) { 
    var p = getUserParams(userID).done(function(userID, q) { 
     //work with userID and q as required 
     $("<p/>").text([userID, q.fullname, q.status, q.postalcode].join(': ')).appendTo($("#results"));//for example 
    }).fail(function(userID, message) { 
     //handle error case here 
     message = message || ''; 
     console.log(['Error', userID, message].join(': '));//for example 
    }); 
    promises.push(p); 
}); 

你也可以做一些事情时,应对ALL ajax请求已收到。如果是这样,则额外的代码看起来就像这样:

$.when.apply(null, promises).done(function() { 
    //Do whatever is required here when ALL ajax requests have successfully responsed. 
    //Note: any single ajax failure will cause this action *not to happen* 
    //alert('All user data was gathered'); 
    console.log('All user data was gathered'); 
}).fail(function() { 
    //Do whatever is required here when ALL ajax requests have responsed. 
    //Note: any single ajax failure will cause this action *to happen* 
    //alert('At least one set of user data failed'); 
    console.log('At least one ajax request for user data failed'); 
}).then(function() { 
    //Do whatever is required here when ALL ajax requests have responsed. 
    //Note: This function will fire after either the done or fail function. 
    //alert('Gathering of user data complete, but not necessarily successfully'); 
    console.log('Gathering of user data complete, but not necessarily successfully'); 
}); 

部分测试(代码运行,但我没有测试Location头的重定向或处理的手段)。

您需要微调代码的某些子集才能精确使用q对象中的用户数据,并适当地处理错误。

0

此功能可以帮助

function getUrl() { 
    var args = {};        // Start with an empty <a title="object" href="http://muraliprashanth.me/category/javascript/object/">object</a> 
    var query = location.search.substring(1); // Get query string, minus '?' 
    var pairs = query.split('&amp;');    // Split at ampersands 
    for(var i = 0; i &lt; pairs.length; i++) { // For each fragment 
     var pos = pairs[i].indexOf('=');  // Look for 'name=value' 
     if (pos == -1) continue;    // If not found, skip it 
     var name = pairs[i].substring(0,pos); // Extract the name 
     var value = pairs[i].substring(pos+1); // Extract the value 
     value = decodeURIComponent(value);  // Decode the value 
     args[name] = value;     // Store as a property 
    } 
    return args;        // Return the parsed arguments 
} 
+0

由于我必须读取重定向数百个重定向到转址后的位置(url),我最好是创建一个带有隐藏iframe的html页面,而不是尝试使用ajax吗?嵌入式iframe的位置是否存在?我知道标准的JavaScript解析当前页面的位置。问题是关于使用制作好的网址,需要到那里并将重定向到我选择的网址,然后才能通过网络cgi为我填充位置,该网址为我提供信息并进行重定向。不幸的是,重定向不是可选的。 – chris