Get JSON return from a URL within the function

Asked

Viewed 120 times

0

I have the following function:

$(document).ready(function(){
arrayAmount[0]='29.90';
}

I need, instead of specifying the value directly there (29.90), it gets the value of a URL.

Ex:

arrayAmount[0]=GET:http://domain_here.com?id=1;

How can I do that?

I need something that is in only one command/line, as there will be several array..

1 answer

0

First set in your javascript:

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

Then use:

var parametro1 = $.urlParam('nome_do_parametro_na_url');

$.urlParam = function(name){
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec("http://dominio.com?id=3&city=SP");
 	return results[1] || 0;
}

var person = new Object();
person.id = $.urlParam("id");
person.city = $.urlParam("city");
console.log(person);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  Substitua <b>http://dominio.com?id=3&city=SP</b> no código acima<br>
  Por <b>window.location.href</b> para pegar a url atual

  • In fact what I need is for it to take the value that the URL returns in JSON, that is, the value is returned only when the URL is accessed. The id=1 is a plan reference, for plan has a different value.

  • If JSON is being passed to the url by GET, just do the same, but using the JS function to convert to JSON var obj = JSON.parse($.urlParam("json");

  • Actually it is not in JSON, it is only in plain text. When access to the URL is displayed on the screen only one value, for example: 79.90

  • In that case your tip will work too?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.