开发者

jquery query parameter parsing - "=" in query string breaks query string up

I'm trying to parse parameters from a query string using this jquery plugin and this sample query string:

http://test.com/?xnJTqqWEclJnnPEvWH&cid=3DF3-00-=63-D4-DA-2F-91-6B-39-39-75-E4-C1-B7-28-12&mid=3D93-36-14-46-4D-52-9E-48-17-=6A-50-13-56-FA-0A-06&PROMO_MONTH=3D201106

Using the code for the plugin:

console.log($.getQueryP开发者_如何学Goaram( "cid" ));

The cid gets divided at the first instance of the "=" sign - so instead of:

3DF3-00-=63-D4-DA-2F-91-6B-39-39-75-E4-C1-B7-28-12

I get

3DF3-00-

Is this normal behavior? Does the equals sign do something in particular in this query string? If not, how do I parse this query string so that I get the entire parameter?


Use gup instead. I see it used in quite a few places and it works well. It is very simple. Note that I made a small change in the fiddle to shoehorn in the url. The code below is what you should actually use.

http://jsfiddle.net/mrtsherman/trqJ8/

gup('cid');

function gup( name )
{
 name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
 var regexS = "[\\?&]"+name+"=([^&#]*)";
 var regex = new RegExp( regexS );
 var results = regex.exec( window.location.href );
 if( results == null )
    return "";
 else
    return results[1];
}


The plugin itself wasn't written to accommodate a string like that. The culprit is the following piece of code...

if (params[0] == param) {
 return params[1] || '';
}

Shortly before this step the plugin script does a split() on the equal sign creating an array. The above code snippet should be changed to something like the following to make your query retrieval work...

if (params[0] == param) {
    var paramOut = '';
    for (var p = 1; p < params.length; p++) {
        paramOut += params[p] + '=';
    }
    return paramOut.substr(0, paramOut.length - 1); // to remove the trailing equal sign
} else {
    return '';
}

Here is the plugin patched with my revisions in case you're still interested in using it...

(function($){$.getQueryParam=function(param){var pairs=location.search.substring(1).split('&');for(var i=0;i<pairs.length;i++){var params=pairs[i].split('=');if(params[0]==param){var paramOut='';for(var p=1;p<params.length;p++){paramOut+=params[p]+'=';}return paramOut.substr(0, paramOut.length-1);}else{return '';}}return undefined;};})(jQuery);


It is. "=" is used as a delimiter of parts of the query, so you should escape it. Yandex search engine does it so: http://yandex.ru/yandsearch?text=%3D

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜