I'm a newbee to JS , JSON and AJAX. I'm using it to develop a simple apps in my SAP env. I'm bit struck in converting the AJAX response to java array. What is have in the code is:
function addTable()
{
var urls = new Array();
$(document).ready(function ()
{
var params = getURLParam().split('?');
$.post("GetBayDetails.htm", {url: getURLParam(), params: params[1]})
.done(function (data)
{
var url = $.parseJSON(data);
urls.push(JSON.parse(url));
$.each(url, function (i, v)
{
push.urls[i] = v.bay;
});
});
});
alert(urls[2]);
}
but if I loop through "URLS" I do not see any value appended to the array. Please can anyone provide some help to get this fixed?
Try this. My changes are:
Use the "json"
dataType argument to $.post
so it parses the response automatically.
There's no need to use $(document).ready()
inside a function that you call on demand. This is only needed when performing initial actions that have to wait for the DOM to be loaded.
It's not necessary to call JSON.parse(url)
, as this is already parsed.
The correct way to add to the urls
array is urls.push(v.bay)
.
The preferred way to initialize an array is with []
, not new Array()
.
alert(urls[2])
needs to be in the .done()
function. Otherwise you're alerting before the AJAX call has completed.
function addTable() {
var urls = [];
var params = getURLParam().split('?');
$.post("GetBayDetails.htm", {url: getURLParam(), params: params[1]}, "json")
.done(function (url) {
$.each(url, function (i, v) {
urls.push(v.bay);
});
alert(urls[2]);
});
}