65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 JavaScript 的 HttpQueryStringBuilder

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.77/5 (7投票s)

2007年6月27日

CPOL
viewsIcon

35242

这是一个实用类,用于从 JavaScript 轻松创建、修改和使用 HTTP 查询字符串。

引言

这段代码可以被认为是一种实用工具,用于使用 JavaScript 从客户端轻松创建、修改和访问带有 GET/POST 的 HTTP 查询字符串。

背景

如今,在使用原始 AJAX 时,我们需要在客户端使用 JavaScript 创建和操作查询字符串,并将其发送到服务器。 有时,特别是当通过查询字符串传输相对大量的数据时,在将其添加到列表后修改其中一个数据项可能会变得很麻烦,等等。

为了帮助这项任务,这个实用工具应该对用户非常有用。 此外,由于它是使用面向对象的 JavaScript 代码开发的,因此易于使用。

使用代码

代码包含两个部分

  1. 实用例程。
  2. Test 方法,演示如何使用该实用例程。
// The class for Creating HTTPQueryString
function HttpQueryStringBuilder()
{
    //Holds the Url
    this.Url = '';    
    //Holds the Array of Key Value Pairs
    this.Pairs = new Array();    
    //The method for getting the final query string
    HttpQueryStringBuilder.prototype.GetFullString = function()
    {
        var queryString = (this.Url.length > 0) ? this.Url + "?" : '';
        for(var key in this.Pairs)
        {
            queryString += escape(key) + "=" + escape(this.Pairs[key]) + "&";
        }
        return queryString.substring(0, queryString.length - 1);
    }
}

////////////////////////////////////////
//
// The Test() Method is added for demonstration purpose only
// Delete this method when you are done with testing
//
////////////////////////////////////////
function Test()
{
    //Define the Object
    var builder = new HttpQueryStringBuilder();
    
    //Supply values
    builder.Url = "http://www.google.com"
    //Pairs[Key] = value (Dont worry about url encoding, it will be handled automatically)
    builder.Pairs["FirstName"] = "S M";
    builder.Pairs["LastName"] = "Sohan";
    builder.Pairs["EMail"] = "sohan39@gmail.com";
    
    //Done with insertions! show it! 
    alert(builder.GetFullString());    
    
    //Make some changes
    builder.Pairs["FirstName"] = "Sheikh Mohammad";
    builder.Pairs["EMail"] = "sohan39@yahoo.com";
    
    //Done with modifications! show it again! 
    alert(builder.GetFullString());    
}

要使用提供的测试代码,您需要在页面中添加如下标记

<script type="text/javascript" src="HttpQueryStringBuilder.js"></script>
<input type="button" value="Button" onClick="Test()" />

历史

  • 2007 年 6 月 30 日:首次编辑,并作为未编辑的文章提交给 CodeProject。
© . All rights reserved.