Riposa gli elementi dell'elenco restituiti ma la risposta è vuota in SP2013
Domanda
Sono soooo frustrato ...
Ho una funzione jquery per afferrare i dati dell'elenco e quando registro "Dati" vedo l'intero {D} con un {risultati} che tiene tutte le voci dell'elenco.Ma quando lo eseguo attraverso una funzione $ .ach per ottenere una stringa che posso tornare, quando accedo RSP, il debugger dice "una stringa vuota."
Ecco la mia funzione:
function get_news(){
var rsp = '';
$.ajax({
url: "http://edrdbdev/_api/web/lists/GetByTitle('Latest News')/items",
type: "GET",
headers: { "accept" : "application/json;odata=verbose" },
success: function(data){
console.log(data);
$.each(data.d.results, function(index, item){
rsp += "<p>" + item.Title + "</p>"
});
},
error: function(error){
rsp = JSON.stringify(error);
}
});
console.log(rsp);
return rsp;
} // end get_props function
.
Sto impazzendo e apprezzerei molto qualsiasi consiglio o correzione.Grazie in anticipo.
Soluzione
$.ajax
perform an asynchronous HTTP (Ajax) request. That means sending the request (or rather receiving the response) is taken out of the normal execution flow.
In your example, return rsp
is executed before the function you passed as success callback was even called.
Solutions
There are basically two ways how to solve this:
- Make the AJAX call synchronous.
- Restructure your code to work properly with callbacks.
Please refer How to return the response from an AJAX call? for a more details
Below is demonstrated the modified version with callback usage:
function get_news(result){
var rsp = '';
$.ajax({
url: "http://edrdbdev/_api/web/lists/GetByTitle('Latest News')/items",
type: "GET",
headers: { "accept" : "application/json;odata=verbose" },
success: function(data){
console.log(data);
$.each(data.d.results, function(index, item){
rsp += "<p>" + item.Title + "</p>"
});
result(rsp);
},
error: function(error){
result(JSON.stringify(error));
}
});
}
//Usage
get_news(function(content){
console.log(content);
});