簡體   English   中英

Javascript 檢查 url 參數是否存在

[英]Javascript check if url param exists

我正在運行 A/B 測試,以查看顯示更多項目是否更適合轉換。 但似乎代碼有時會導致錯誤..但我找不到任何錯誤,也不知道它們何時發生。

在我的測試中,我檢查 url 參數 IC 是否存在,如果不存在,我將添加它。

這是我的代碼:

function checkIfAlreadyPaginated()
  {
        var field = 'IC';
    var url = window.location.href;
    if(url.indexOf('?' + field + '=') != -1)
        return true;
    else if(url.indexOf('&' + field + '=') != -1)
        return true;
    return false;
  }
function insertParam(key, value) {
        key = encodeURIComponent (key); value = encodeURIComponent (value);

        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            return '?' + key + '=' + value;
        }
        else {

            var i = kvp.length; var x; while (i--) {
                x = kvp[i].split('=');

                if (x[0] == key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i < 0) { kvp[kvp.length] = [key, value].join('='); }

            return '?'+kvp.join('&');
        }
    }
var itemsPerPage = 48;
if(!checkIfAlreadyPaginated())
    {
      document.location.search = insertParam('IC', itemsPerPage);
    }

有人發現可能的問題嗎? 我正在通過 VWO.com 運行測試。

如果出現 Javascript 錯誤,您應該在瀏覽器控制台中看到它並與我們分享。

無論如何,我會先創建一個 JS 對象。 我覺得合作起來更容易。

在下面的代碼中,我添加了檢查查詢字符串的多個參數的選項。 如果您只需要檢查IC,您可以稍微簡化一下。 我在一個空白的 test.html 上測試了它。

<script type="text/javascript">
// get the current params of the querystring
var querystringItems = document.location.search.substr(1).split('&');

// create an object
var querystringObject = {};
for(i=0;i<querystringItems.length;++i) {
    param = querystringItems[i].split('=');
    querystringObject[param[0]] = param[1];
}

// Define the keys to be searched for and their default value when they are not present
var requiredKeys = {"IC":48, "test": "me"};

// Do the checking on the querystringObject for each requiredKeys
var doreload = false;
for (var key in requiredKeys) {
    if (typeof querystringObject[key] == 'undefined') {
        doreload = true;
        // Create the missing parameter and assign the default value
        querystringObject[key] = requiredKeys[key];
    }
}

// If any of the requiredKeys was missing ...
if (doreload) {
    // rebuild the querystring
    var querystring = '?';
    for (var key in querystringObject) {
        querystring+=key+'='+querystringObject[key]+'&';
    }
    querystring=querystring.substr(0,querystring.length-1);
    // reload page
    document.location.search = querystring;
}

// assign the values to javascript variables (assuming you had it like this because you needed it)
var itemsPerPage = querystringObject.IC;
</script>

這是一個檢查這個的例子:

//get URL params into string:
paramStr = window.location.substring(window.location.indexOf('?'), window.location.length;
//turn string into array
paramArray = paramStr.split('&');
//prepare final array of params
params = {};
//prepare the index of IC parameter
icLoc = -1; //this is negative 1 so that you know if it was found or not
//for each item in array
for(var i in paramArray){
    //push its name and value to the final array
    params.push(paramArray[i].split('='));
    //if the parameter name is IC, output its location in array
    if(params[i][0] === 'IC'){
        icLoc = i;
    }
}

如果未找到 IC,則 icLoc 將為-1

如果找到,則URL參數中IC的值為params[icLoc][1]


查詢字符串?foo=bar&code=cool&IC=HelloWorld示例結果:

 params = {'foo': 'bar', 'code': 'cool', 'IC': 'HelloWorld'} icLoc = 2


查詢字符串示例?foo=bar&code=cool

 params = {'foo': 'bar', 'code': 'cool'} icLoc = -1

這里 id 是我用於測試的參數。 傳遞要檢查它是否存在的參數。

 function queryParamExistUrl(param = '') { if (new URLSearchParams(window.location.search).get(param) != null) return true return false } console.log(queryParamExistUrl('id'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM