How to parse the first line of the http header? - javascript

Is there any javascript function, to parse the first line of the http header?
GET /page/?id=173&sessid=mk9sa774 HTTP/1.1
The url is encoded.
I would like to get an object, like this:
{
"method" : "GET",
"url" : "/page/",
"parameters": {
"id" : 173,
"sessid" : "mk9sa774"
}
}
I searched a lot, but I haven't found anything useful.
thanks in advance,

First you can split on spaces:
var lineParts = line.split(' ');
Now you can get the method, unparsed path, and version:
var method = lineParts[0];
var path = lineParts[1];
var version = lineParts[2];
Then you can split up the path into the query string and non-query string parts:
var queryStringIndex = path.indexOf('?');
var url, queryString;
if(queryStringIndex == -1) {
url = path, queryString = '';
}else{
url = path.substring(0, queryStringIndex);
// I believe that technically the query string includes the '?',
// but that's not important for us.
queryString = path.substring(queryStringIndex + 1);
}
If there is a query string, we can then split it up into key=value strings:
var queryStringParts = [];
if(queryStringIndex != -1) {
queryStringParts = queryString.split('&');
}
Then we can unescape them and stuff them into an object:
var parameters = {};
queryStringParts.forEach(function(part) {
var equalsIndex = part.indexOf('=');
var key, value;
if(equalsIndex == -1) {
key = part, value = "";
}else{
key = part.substring(0, equalsIndex);
value = part.substring(equalsIndex + 1);
}
key = decodeURIComponent(key);
value = decodeURIComponent(value);
parameters[key] = value;
});
If you really wanted to, you could then put all that data into an object:
return {
method: method,
url: url,
version: version,
parameters: parameters
};
If you're in a browser environment, that's the only way to do it. If you're using Node.JS, it can deal with the URL parsing for you.

Related

Convert nested form fields to JSON in Jquery

Trying to do POST of Form object as JSON from front end javacsript/jquery to Spring MVC backend.
Form data has a string array and other string field, looks like below
...
var cityList = [];
citylist.push("SF");
citylist.push("LA");
document.forms["myForm"]["dstCities"].value = cityList;
document.forms["myForm"]["dstState"].value = "CA";
...
Below is my code for converting to JSON,
function convertFormToJSON(){
var jsonObject = {};
var array = $("myForm").serializeArray();
$.each(array, function() {
if (jsonObject[this.name] !== undefined) {
jsonObject[this.name].push(this.value || '');
} else {
jsonObject[this.name] = this.value || '';
}
});
jsonObject = JSON.stringify(jsonObject);
console.log("json: " + jsonObject);
return jsonObject;
};
POST call:
$.ajax({
url: "xxx",
type: "POST",
data: convertFormToJSON(),
contentType: "application/json",
dataType: 'json',
...
});
Json output:
{"dstCities":"SF,LA", "dstState":"CA"}
But I need it to look like
[{"dstCities": ["SF", "LA"], "dstState":"CA"}]
You are passing an array as value to :
document.forms["myForm"]["dstCities"].value = cityList;
but the browser is using toString() on it and it ends up as joined string "SF,LA"
If the intent is to pass it as string array can do:
document.forms["myForm"]["dstCities"].value = JSON.stringify(cityList);
No changes would be needed in convertFormToJSON this way.
If the cities need to be displayed as comma separated values then change
if (jsonObject[this.name] !== undefined) {
jsonObject[this.name].push(this.value || '');
} else {
var value = this.value;
if (this.name === 'dstCities') {
value = value.split(',');
}
jsonObject[this.name] = value || '';
}

jQuery append params to url

I like the way jQuery's $.ajax() method allows to specify request url:
{
url: 'http://domain.com/?param=1',
data{
param2: '2'
}
}
$.ajax() method will (probably) call $.param() on provided data and optionally append it to provided URL.
My question is: is this type of url manipulation available outside of $.ajax() call?
For example, I want to open a popup window, and I would like to construct URL in the same way that I do with $.ajax().
I have written a function which does this, but I have a feeling I am reinventing the wheel and duplicating already existing function of jQuery:
var prepareUrl = function( url, data )
{
var params = $.param( data );
if ( params.length > 0 )
{
// url contains a query string
if ( url.indexOf( '?' ) > -1 )
{
// get last char of url
var lastChar = url.substr( url.length - 1 );
// Append & to the end of url if required
if ( lastChar != '&' && lastChar != '?' )
{
url += '&';
}
}
else // url doesn't contain a query string
{
url += '?';
}
url += params;
}
return url;
}
thanks!
Since other replies didn't answer my question, i have made a few tests with the $.ajax() call to see how it merges urls with param data.
My findings so far:
if url contains a ?, then $.ajax() will append '&' + $.param(data)
if not, then $.ajax() will append '?' + $.param(data)
So if I want to keep my url processing function consistent with the way $.ajax() does it, then it should be something like the following:
var addParams = function( url, data )
{
if ( ! $.isEmptyObject(data) )
{
url += ( url.indexOf('?') >= 0 ? '&' : '?' ) + $.param(data);
}
return url;
}
I am still wondering if there is a built-in jQuery method to do this.
You can build query string like this:
getQueryStr = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
console.log(serialize({
param1: "val1",
param2: "val2"
}));
For recursive :
getQueryStr = function(obj, prefix) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push(typeof v == "object" ?
getQueryStr(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
console.log(serialize({
favfruit: "apple",
data: {
name: 'js',
points: [1, 2, 3]
}
}));
yes you can use jqueries .param() function to do this.
jsfiddle demo
var params = { param1:"foo", param2:"bar"};
var str = jQuery.param( params );
alert(str);
The param method will generate a query string for you, but you will need to to remove the existing query string.
var base = "http://example.com/foo/?example=old";
var data = {
foo: "hello",
bar: "world?"
};
var url = base.replace(/\?.*$/, "") + "?" + jQuery.param(data);
alert(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
As mentioned in this SO answer, just use URLSearchParams
let urlParams = new URLSearchParams(location.search.substr(1));
urlParams.set(key, value);
where key=value is new url parameter that you want to add
You could check the browser compatibility here

Splitting up a string and passing it to a function

I am having some trouble trying to pass string objects to a function. In the query string of the url I pass fields which is a comma delimited string containing the attributes of interest.
I put the names of those attributes in the fields array. However now I am having trouble passing that information to a function.
In the code below the query.pluck('id', 'name') works, the query.pick( fieldString ) does not.
I am stuck on this one, how can I pass the attribute names in the fields array to the function so it will work?
Please advice.
var log = require('logule').init(module,'query');
var url = require('url');
module.exports = {
build : function(req, entity, callback) {
var isCollection;
isCollection = req.params.id? false: true;
var query = req.rethink.table(entity);
parsedUrl = url.parse(req.url, true);
console.log(isCollection);
if (parsedUrl.query.fields) {
var fields = parsedUrl.query.fields.split(',');
var total = fields.length;
fieldString = fields[0];
for (var i = 1; i < total; i++) {
fieldString += ', ' + fields[i];
}
if (isCollection) {
var query = query.pluck('id', 'name');
} else {
var query = query.get(req.params.id).pick( fieldString );
}
}
return callback(null, query);
}
}
You don't need to put fields in a string, just use
var query = query.get(req.params.id).pick.apply(this,fields);
You need to use the "apply" function with the function name, and an array of parameters (fields in your case)
var query = query.get(req.params.id).apply('pick', fields);

Getting URL data with JavaScript (split it like php $_GET)

I found this script at Stack Overflow:
window.params = function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for(var i in param_array){
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
}();
This splits a URL into data, like PHP does with $_GET.
I have another function, which uses it and it refreshes the iframe. I want to get the data from the URL and add another with it if some of these data exist. Firebug shows me, that search is not defined, but why?
function RefreshIFrames(MyParameter) {
var cat = window.params.cat;
var category = window.params.category;
var search = window.params.search;
if (search.length>0 && category.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search="+search+"&category="+category+"&rendez="+MyParameter;
}
if (cat.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat="+cat+"&rendez="+MyParameter;
}
if (cat.length==0 && category.length==0 && search.length==0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez="+MyParameter;
}
alert(window.location);
}
If you want to add rendez OR change the existing rendez, do this - I am assuming the URL is actually beginning with http://siriusradio.hu/kiskunfelegyhaza/video/index.php so no need to create it. Let me know if you need a different URL than the one you come in with
The parameter snippet did not work proper (for in should not be used on a normal array)
Here is tested code
DEMO
DEMO WITH DROPDOWN
function getParams(passedloc){
var params = {}, loc = passedloc || document.URL;
loc = loc.split('?')[1];
if (loc) {
var param_array = loc.split('&');
for(var x,i=0,n=param_array.length;i<n; i++) {
x = param_array[i].split('=');
params[x[0]] = x[1];
}
}
return params;
};
function RefreshIFrames(MyParameter,passedloc) { // if second parm is specified it will take that
var loc = passedloc || document.URL; //
window.param = getParams(loc);
loc = loc.split("?")[0]+"?"; // will work with our without the ? in the URL
for (var parm in window.param) {
if (parm != "rendez") loc += parm +"="+ window.param[parm]+"&";
}
// here we have a URL without rendez but with all other parameters if there
// the URL will have a trailing ? or & depending on existence of parameters
loc += "rendez="+MyParameter;
window.console && console.log(loc)
// the next statement will change the URL
// change window.location to window.frames[0].location to change an iFrame
window.location = loc;
}
// the second parameter is only if you want to change the URL of the page you are in
RefreshIFrames("rendez1","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat=cat1&search=search1");
RefreshIFrames("rendez2","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search=search2");
RefreshIFrames("rendez3","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez=xxx&search=search2");
RefreshIFrames("rendez4","http://siriusradio.hu/kiskunfelegyhaza/video/index.php");
// here is how I expect you want to call it
RefreshIFrames("rendez5"​); // will add or change rendez=... in the url of the current page

Support for encoding query string or POST data in YUI?

How do you encode a javascript object/hash (pairs of properties and values) into a URL-encoded query string with YUI (2.7.0 or 3.0.0 Beta) ?
I want to do the equivalent of Object.toQueryString() from Prototype:
I need this to encode parameters for GET and POST requests with YAHOO.util.Connect.
It turns out YAHOO.util.Connect has a setForm() method to serialize a form but that still leaves me out cold to encode parameters for GET requests, or the 4th parameter of YAHOO.util.Connect.asyncRequest() to pass post data.
I've made this little helper for my own project.
var toQueryString = function(o) {
if(typeof o !== 'object') {
return false;
}
var _p, _qs = [];
for(_p in o) {
_qs.push(encodeURIComponent(_p) + '=' + encodeURIComponent(o[_p]));
}
return _qs.join('&');
};
// And to use it
var qs = toQueryString({'foo' : 'bar'});
YUI3 has the io-form module, which you can instantiate in your call the use. It allows you to write code like this:
YUI().use('node', 'io-form', function(Y) {
Y.get('#formId').on('sumbit', function(e) {
e.preventDefault();
Y.io(postURL,
{
method: "POST",
on: {
complete: on_complete_handler
},
form: {
id: "formId"
}
});
}
});
This code will make a POST request to postURL, with all the input values from the form with id "formId" is submitted. This module also works for GET requests.
I ended up using something like this based on some code found on github. The function must handle posting arrays..
"Y" is a reference to "YAHOO"
/**
* Turns an object into its URL-encoded query string representation.
*
* #param {Object} obj Parameters as properties and values
*/
toQueryString: function(obj, name) {
var i, l, s = [];
if (Y.lang.isNull(obj) || Y.lang.isUndefined(obj)) {
return name ? encodeURIComponent(name) + '=' : '';
}
if (Y.lang.isBoolean(obj)) {
obj = obj ? 1 : 0;
}
if (Y.lang.isNumber(obj) || Y.lang.isString(obj)) {
return encodeURIComponent(name) + '=' + encodeURIComponent(obj);
}
if (Y.lang.isArray(obj)) {
name = name; // + '[]'; don't do this for Java (php thing)
for (i = 0, l = obj.length; i < l; i ++) {
s.push(arguments.callee(obj[i], name));
}
return s.join('&');
}
// now we know it's an object.
var begin = name ? name + '[' : '',
end = name ? ']' : '';
for (i in obj) {
if (obj.hasOwnProperty(i)) {
s.push(arguments.callee(obj[i], begin + i + end));
}
}
return s.join("&");
}
I see YUILibrary Ticket 2528174 refers to an accepted contribution on for this.
The Querystring Utility
Provides static methods to serialize objects to querystrings and deserialize objects from querystrings.
Three modules are available:
querystring - Both parse and stringify functionality
querystring-parse - Parse valid querystring into JavaScript objects
querystring-stringify - Serialize JavaScript objects into valid query strings

Categories

Resources