How to save a Json in a variable javascipt

1

hi chic @ s I have a problem. I'm designing a web in which I use a php script that searches in several directories of my web images that comply with certain characters in its name, and once it has this it returns the link in json format.

My problem is when I create a javascipt code that consists of a function that through ajax retrieves that link and I want to save it in a variable. I have tried with async: false and also creating a function outside the ajax and calling it from the ajax to save the variable but I can not do it. I'm blocked and I do not know how to continue. Someone can throw some light on me.

Greetings and thanks

---- EDIT -----

I did not put the code because I thought it was unnecessary. I put it this way:

When anywhere I need to look for the image by js I call it in a javascript function:

buscar_imagen(atributo);

and the ajax looking for the image in question

function buscar_imagen(atributo){
   $.ajax({
    type: 'GET',
    url: 'buscar_imagen.php?ruta='+atributo[0]+'&id='+atributo[1],
    crossDomain: true,
    scriptCharset: 'UTF-8',
    cache:false,
    dataType: 'jsonp',
    async: false,
    success: function (data) {
       variable_global=data;
    },
    error: function () {
       variable_global='url_alternativa';
    }
   });
 return variable_global;
 }

As you can deduce what I want is that when I call search_image () this returns the link I need.

Thanks

    
asked by Jonatan 29.08.2018 в 22:46
source

1 answer

1

The only way to return data from the function would be to make a synchronous call instead of an asynchronous call, but that would freeze the browser while waiting for the response.

You must implement a CallBack, attach the link to SO

According to the example given there, you have:

function testAjax(handleData) {
  $.ajax({
    url:"getvalue.php",  
    success:function(data) {
      handleData(data); 
    }
  });
}

Modified

testAjax(function(output){
  // acá sacas el resultado
});

It would be this:

buscar_imagen(function(atributo){

})
    
answered by 30.08.2018 / 14:53
source