Descansa los artículos de la lista de devoluciones, pero la respuesta está en blanco en SP2013

sharepoint.stackexchange https://sharepoint.stackexchange.com//questions/90325

  •  10-12-2019
  •  | 
  •  

Pregunta

Estoy tan frustrado ...

Tengo una función jQuery para agarrar los datos de la lista y cuando registro "DATOS", veo el {D} completo con un {resultados} que sostiene todos los elementos de la lista.Pero cuando lo ejecuto a través de una función de $ ..eña para obtener una cadena, puedo volver, cuando logro RSP, el depurador dice "una cadena vacía".

Aquí está mi función:

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

Me estoy volviendo loco y apreciaría mucho cualquier consejo o corrección.Gracias de antemano.

¿Fue útil?

Solución

$.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);
});
Licenciado bajo: CC-BY-SA con atribución
scroll top