2012-12-06 139 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