0
At this moment I find myself working on a project, and I need to call a webservice that should resume a json, so that later it can be interpreted and fill a dropdown list. Actually, part of the code that I need for this work, I’ve already found it in an article here on the web, but there’s a problem. JSON, is stored in a local variable, and I need to get the same from a REST webservice.
<script type="text/javascript">
var myjson;
$.getJSON("http://localhost:8080/revistaSystem/resplaneamento/ServicoComposicao/ObterTodasAsComposicoes/", function(json){
myjson = json;
console.log(json);
});
function PopulateDropDownList() {
//Build an array containing Customer records.
/*
var customers = [
{ CustomerId: 1, Name: "John Hammond", Country: "United States" },
{ CustomerId: 2, Name: "Mudassar Khan", Country: "India" },
{ CustomerId: 3, Name: "Suzanne Mathews", Country: "France" },
{ CustomerId: 4, Name: "Robert Schidner", Country: "Russia" }
];*/
var customers = myjson;
var ddlCustomers = document.getElementById("ddlCustomers");
//Add the Options to the DropDownList.
for (var i = 0; i < customers.length; i++) {
var option = document.createElement("OPTION");
//Set Customer Name in Text part.
option.innerHTML = customers[i].Name;
//Set CustomerId in Value part.
option.value = customers[i].CustomerId;
//Add the Option element to DropDownList.
ddlCustomers.options.add(option);
}
}
</script>
I must get the json and process it before the page is fully loaded, so I opted for the html page:
<body onload="PopulateDropDownList()">
</body>
As you can see above I intend to load the JSON,and made some attempts that failed. As well as working with php, in this project I also tried to get JSON from PHP, to later put it next to javascript. I’ve had enough trouble.
<?php
$uri ="http://localhost:8080/revistaSystem/resplaneamento/ServicoComposicao/ObterTodasAsComposicoes/";
$json = file_get_contents($uri);
$obj = json_decode($json, true);
echo json_encode($obj);
?>
Summary: I must get the JSON,from a URI, and after getting this, fill a dropdown list, with values. This whole process has to be accomplished before loading the page. Just out of curiosity, calling my REST webservice, it returns JSON in the following format :
[{"numPK":1,"composicao":"100% Algodao"},{"numPK":2,"composicao":"40% Linho/60% Algodao"},{"numPK":3,"composicao":"30% Linho/70% Algodao"}]
I wonder if you could give me a concrete example. Thanks in advance!
$.getJSON
is asynchronous and will not wait to capture the result and then display. The correct thing is to call the functionPopulateDropDownList
within the callback of$.getJSON
, instead ofonload
. If you need to make this request before the page is loaded, I advise adding a screen of loading instead of using synchronous requests.– Valdeir Psr