简体   繁体   English

使用javascript读取/操作查询字符串参数的最简单方法是什么?

[英]What is the easiest way to read/manipulate query string params using javascript?

The examples I've seen online seem much more complex than I expected (manually parsing &/?/= into pairs, using regular expressions, etc). 我在网上看到的例子似乎比我预期的要复杂得多(手动解析&/?/ =成对,使用正则表达式等)。 We're using asp.net ajax (don't see anything in their client side reference) and would consider adding jQuery if it would really help. 我们正在使用asp.net ajax (在客户端参考中看不到任何内容)并且会考虑添加jQuery,如果真的有帮助的话。

I would think there is a more elegant solution out there - so far this is the best code I've found but I would love to find something more along the lines of the HttpRequest.QueryString object (asp.net server side) . 我认为那里有一个更优雅的解决方案 - 到目前为止这是我发现的最好的代码,但我希望找到更多的HttpRequest.QueryString对象(asp.net服务器端) Thanks in advance, 提前致谢,

Shane 巴蒂尔

确实有一个jQuery的QueryString插件 ,如果你愿意安装jQuery核心和插件它可能证明是有用的。

I am using this function in case i don't want to use a plugin: 我正在使用此功能,以防我不想使用插件:

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return null;
}

Take a look at my post, as it tells you exactly how to do this: 看看我的帖子,因为它告诉你具体如何做到这一点:

http://seattlesoftware.wordpress.com/2008/01/16/javascript-query-string/ http://seattlesoftware.wordpress.com/2008/01/16/javascript-query-string/

For jQuery I suggest jQuery BBQ: Back Button & Query Library By "Cowboy" Ben Alman 对于jQuery我建议jQuery BBQ:Back Button&Query Library由“Cowboy”Ben Alman提供

jQuery BBQ leverages the HTML5 hashchange event to allow simple, yet powerful bookmarkable #hash history. jQuery BBQ利用HTML5 hashchange事件来允许简单但功能强大的可收藏的#hash历史记录。 In addition, jQuery BBQ provides a full .deparam() method, along with both hash state management, and fragment / query string parse and merge utility methods. 此外,jQuery BBQ提供了完整的.deparam()方法,以及散列状态管理和片段/查询字符串解析和合并实用程序方法。

Example: 例:

// Parse URL, deserializing query string into an object.
// http://www.example.com/foo.php?a=1&b=2&c=hello#test
// search is set to ?a=1&b=2&c=hello
// myObj is set to { a:"1", b:"2", c:"hello" }
var search = window.location.search;
var myObj = $.deparam.querystring( search );
  *$(document).ready(function () {
            $("#a").click(function () {
                window.location.href = "secondpage.aspx?id='0' & name='sunil'& add='asr' & phone='1234'";
            });
        });*


**then read the query string parameters on another using split method . Here as follows:**


  *$(document).ready(function () {
            var a = decodeURI(window.location.search);
            var id = window.location.search = "id=" + $().val();
            var name = a.split("name=")[1].split("&")[0].split("'")[1];
            var phone = a.split("phone=")[1].split("&")[0].split("'")[1];
            var add = a.split("add=")[1].split("&")[0].split("'")[1];
            alert(id+','+name+','+add+','+phone); 
        });*

If there's any possibility of encountering repeated parameters (eg ?tag=foo&tag=bar), most libraries out there won't be sufficient. 如果有可能遇到重复参数(例如?tag = foo&tag = bar),那么大多数库都不够用。 In that case, you might want to consider this library that I developed from Jan Wolter's very comprehensive parser . 在这种情况下,您可能想要考虑我从Jan Wolter 非常全面的解析器开发的这个库。 I added .plus() and .minus() functions and roundtripping: 我添加了.plus()和.minus()函数和往返:

https://github.com/timmc/js-tools/blob/master/src/QueryString.js https://github.com/timmc/js-tools/blob/master/src/QueryString.js

Use the String utility from prototypejs.org, called toQueryParams(). 使用来自prototypejs.org的String实用程序,名为toQueryParams()。

Example from their site: http://prototypejs.org/api/string/toQueryParams 来自他们网站的示例: http//prototypejs.org/api/string/toQueryParams

'section=blog&id=45'.toQueryParams(); “部分=博客&ID = 45'.toQueryParams();
// -> {section: 'blog', id: '45'} // - > {section:'blog',id:'45'}

'section=blog;id=45'.toQueryParams(); “部分=博客; ID = 45'.toQueryParams();
// -> {section: 'blog', id: '45'} // - > {section:'blog',id:'45'}

' http://www.example.com?section=blog&id=45#comments '.toQueryParams(); ' http://www.example.com?section=blog&id=45#comments'.toQueryParams ();
// -> {section: 'blog', id: '45'} // - > {section:'blog',id:'45'}

'section=blog&tag=javascript&tag=prototype&tag=doc'.toQueryParams(); “部分=博客&标签= JavaScript的&标签=原型&标签= doc'.toQueryParams();
// -> {section: 'blog', tag: ['javascript', 'prototype', 'doc']} // - > {section:'blog',tag:['javascript','prototype','doc']}

'tag=ruby%20on%20rails'.toQueryParams(); “标记=红宝石%20on%20rails'.toQueryParams();
// -> {tag: 'ruby on rails'} // - > {tag:'ruby on rails'}

'id=45&raw'.toQueryParams(); “ID = 45&raw'.toQueryParams();
// -> {id: '45', raw: undefined} // - > {id:'45',raw:undefined}

Also, you may use the alias parseQuery() to obtain the same results. 此外,您可以使用别名parseQuery()来获得相同的结果。

window.location.search.parseQuery();

Since window.location returns an object, you must obtain the string. 由于window.location返回一个对象,因此必须获取该字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 基于javascript中的模板来选择字符串部分的最简单方法是什么 - What is the easiest way to pick portions of a string based on a template in javascript 在javascript中本地化字符串的最简单方法 - Easiest way to localize string in javascript 使用JS在字符串中找出字符重复的最简单方法是什么? - What is the easiest way to find out character repetition in a string using JS? 使用javascript在字符串中添加单个数字的最简单方法是什么 - What is the easiest method to add individual numbers in a string using javascript 读取URL中的单个变量的最简单方法是什么? - What is the easiest way to read a single variable in a URL? 更改数组值的最简单方法是什么 javascript - What is the easiest way of changing the values of an array javascript 将服务器返回的字符串分配给javascript字符串最简单的方法是什么? - What's the easiest way to assign a string returned from the server to a javascript string? 给定一个表示XML文件的字符串,用Javascript或jQuery查找所有名称空间声明的最简单方法是什么? - Given a string representing an XML file, what's the easiest way to locate all namespace declarations with Javascript or jQuery? 用户可以使用javascript或任何其他方式来操纵只读字段中的值吗? - Can users manipulate values from read-only fields using javascript or any other way? 使用javascript从excel电子表格中读取数据的最简单方法? - easiest way to read data from excel spreadsheet with javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM