2011-07-26 47 views
0

CakePHP URL查詢參數不是以標準方式完成的,例如,的PARAMS是/參數1:數值1 /參數2:VALUE2代替參數1 =值1 &參數2 =值2在CakePHP中使用JavaScript訪問URL查詢參數

這意味着location.search不返回值的JavaScript?。

有一個getQueryParams JQuery plugin是我想要做什麼用location.search

我不得不修改此使用

var pairs = location.pathname.split('/'); 

,而不是

var pairs = location.search.substring(1).split('&'); 

但是現在這個包括一切但變量pairs中的主機除外。所以我必須檢查一個':'來查看它是否是一個參數。

這有用 - 但有沒有更好的(更像蛋糕)的方式呢?我不想改進JQuery插件(例如Regex),我想找到一種更好的方式來將插件與CakePHP集成。

Upddate:我已經刪除了jQuery代碼的其餘部分,我很高興與jQuery代碼,我的問題是與蛋糕

更貼它是否有某種方式「像蛋糕」從location.pathname中刪除您的應用程序,模型和控制器的路徑,以便最終獲得您通常從location.search獲得的內容?

回答

0

所以它似乎沒有這樣做的更好的方法。以下是供參考的javascript:

// jQuery getQueryParam Plugin 1.0.1 (20100429) 
// By John Terenzio | http://plugins.jquery.com/project/getqueryparam | MIT License 
// Modified by ICC to work with cakephp 
(function ($) { 
    // jQuery method, this will work like PHP's $_GET[] 
    $.getQueryParam = function (param) { 
     // get the pairs of params fist 
     // we can't use the javascript 'location.search' because the cakephp URL doesn't use standard URL params 
     // e.g. the params are /param1:value1/param2:value2 instead of ?param1=value1&param2=value2 
     var pairs = location.pathname.split('/'); 
     // now iterate each pair 
     for (var i = 0; i < pairs.length; i++) { 
      // cakephp query params all contain ':' 
      if (pairs[i].indexOf(':') > 0) { 
       var params = pairs[i].split(':'); 
       if (params[0] == param) { 
        // if the param doesn't have a value, like ?photos&videos, then return an empty srting 
        return params[1] || ''; 
       } 
      } 
     } 
     //otherwise return undefined to signify that the param does not exist 
     return undefined; 
    }; 
})(jQuery); 
1

既然你正在尋找一個特定的參數,你可以使用正則表達式:

$.getQueryParam = function (param) { 
    var re = new RegExp(param+':([^\/]+)'); 
    var matches = location.pathname.match(re); 
    if (matches.length) { 
     return matches[1]; 
    } 
    return undefined; 
} 
+0

謝謝@chrisdpratt,抱歉讓我感到困惑,但我正在尋找方法將它更好地整合到蛋糕中。我爲此編輯了這個問題。 – icc97