Samuel Moshie
Samuel Moshie

Reputation: 570

How to parse data via url and retrive with javascript

I went through sb code and wants to implement similar code. he used:

  htmlItems += '<li><a href="show-feed.html?url=' + items[i].url + '">' + 
  items[i].name + '</a></li>';

and used this javascript code to retrive the url and parse to a method

.on('pageinit', '#show-feed-page', function () {
        var url = this.getAttribute('data-url').replace(/(.*?)url=/g, '');
        Application.initShowFeedPage(url);

it works well and i want to parse three values to the method eg <a href="showProduct.html?code='+ items[i].code +',name='+items[i].name+',price='+items[i].price+'">"and need code to retrive and parse to a method

initShowProductPage(code,name,price);

Upvotes: 1

Views: 149

Answers (1)

Shaik Mahaboob Basha
Shaik Mahaboob Basha

Reputation: 1082

First of all, your html is wrong, you have to prepare proper query string format, the updated html mark up is:

    <a href="showProduct.html?code='+ items[i].code +
      '&name='+items[i].name+'&price='+items[i].price+'">"

You have to access window.location.href and parse it for the query string parameters.You can write a method which parses the url, like below:

 function parseURL() {
       var vars = [];
       var hashes = window.location.href.slice( window.location.href.indexOf('?')+1 ).split("&");
       for (var i=0;i<hashes.length;i++) {
            hash = hashes[i].split("=");
            vars.push( hash[0] );
            vars[ hash[0] ] = hash[1];
       }
       return vars;
}

Then you can access them using code, name and price parameters like below:

.on('pageinit', '#show-feed-page', function () {
      var hashObj = parseURL();
      // To get code
      var code =  hashObj["code"];

      // To get name
      var name = hashObj["name"];

      // To get price
      var price = hashObj["price"];

      // Now call the method
      initShowProductPage(code,name,price);

});

Upvotes: 2

Related Questions