Introduction
This code may be considered as a utility tool for creating, modifying, accessing HTTP querystrings with GET/POST, very easily using JavaScript from the client side.
Background
Nowadays, when working with raw AJAX, we need to create and manipulate the query strings at the client side using JavaScript and send it to the server. Sometimes, specially when relatively large data are transmitted in querystrings, it may get painful to modify one of the data items once added to the list, and so on.
To help this task, this utility should be very helpful to its users. Also, it is simple to use as it is developed using object oriented JavaScript code.
Using the code
The code contains two segments:
- The utility routine.
- The
Test
method demonstrating how to make use of the utility routine.
function HttpQueryStringBuilder()
{
this.Url = '';
this.Pairs = new Array();
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);
}
}
function Test()
{
var builder = new HttpQueryStringBuilder();
builder.Url = "http://www.google.com"
builder.Pairs["FirstName"] = "S M";
builder.Pairs["LastName"] = "Sohan";
builder.Pairs["EMail"] = "sohan39@gmail.com";
alert(builder.GetFullString());
builder.Pairs["FirstName"] = "Sheikh Mohammad";
builder.Pairs["EMail"] = "sohan39@yahoo.com";
alert(builder.GetFullString());
}
To use the supplied test code, you need a markup like this in one of your pages:
<script type="text/javascript" src="HttpQueryStringBuilder.js"></script>
<input type="button" value="Button" onClick="Test()" />
History
- June 30, 2007: Edited for the first time, and submitted as unedited post to CodeProject.