Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery $getJSON How do I dynamically create data for the [data] parameter after Url param?

I have no problems getting the Json to work and parse the json return. I was just wondering how I could build a dynamic "whatever data is" and stick it into [data] to pass my parameters from there and not manually append them to the url.

From jquery website example:

$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){
     alert("JSON Data: " + json.users[3].name);
});

I thought I could build a string ( which doesn't make sense anyway ) and drop it inside the { }, but I obviously don't understand that part.

name: isn't a string and you can't put a variable in that part, so how would I dynamically put items into whatever [data] is.

UPDATE: Thanks for the answers. Would I be able to remove a parameter name from the object if I didn't find a valid value later on or would I need to destroy it and recreate it? I am using some select boxes to choose things and I may not have something selected so I wouldn't want to pass that parameter name/value.

like image 516
Breadtruck Avatar asked Mar 14 '10 12:03

Breadtruck


People also ask

What does getJSON do?

The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

What does getJSON return?

getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. The method returns XMLHttpRequest object.

How jQuery read data from JSON file?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.


1 Answers

You can build your object like this:

var someVar = someRandomString();
$.getJSON('test.js', (function() {
  var theData = {};
  theData[someVar] = someRandomValue();
  return theData;
})(), function(jsonStuffFromServer) {
  alert("JSON Data: " + jsonStuffFromServer.users[3].name);
});

Of course you don't have to build up the "data" object right there in an anonymous function; you can do it separately beforehand:

var theData = {};
theData[someVariableWithANameInIt] = someRandomValue();
$.getJSON(url, theData, function(jsonStuff) { ... });

Here's how you could build up such an object from a set of <select> elements on your page:

var theData = {};
$('#myForm select').filter(function() { return $(this).val() != ''; })
  .each(function() {
    theData[this.name] = $(this).val();
  });

$.getJSON(url, theData, function(jsonStuff) { ... });
like image 76
Pointy Avatar answered Nov 05 '22 00:11

Pointy