Get an html and save in variable

1

I have a simple html in file and I want to ghetto it in a variable to use, I did the get like this:

 let popup = '';
 $.get( "popup.html", function( data ) {
     // the contents is now in the variable data
     console.log("data"+data);
     popup =  data;
 });
 console.log("popup"+popup);

But it is not saving in popup, the log is:

    popup
(index):247 data<p style="font-weight: bold;font-size: 16px" id="nome">a</p>
<div class="dropdown-divider w-50 mx-auto "></div>
<p  id="endereco">c</p>
<p  id="tel">dc</p>
<p  id="email">ca</p>

    

asked by anonymous 09.03.2018 / 18:06

2 answers

4

You are calling an asynchronous function ( $.get ) and wanting to assign the return to the variable popup before it returns some value. You could use the $.ajax method with the async: false parameter, but it is not recommended because of the warning:

  

Synchronous XMLHttpRequest on the main thread is deprecated because of   its detrimental effects to the end user's experience

     

Learn more in this topic ...

What you can do is call a function that returns the value of data of $.get after it is processed, using .then() :

function htmlPopup(){
   return $.get( "popup.html").then(function(data){
      return data;
   });
}

htmlPopup().then(function(popup){
   console.log(popup);

   // resto do código que irá usar a variável popup

});
    
09.03.2018 / 21:16
-2
popup = $.get( "popup.html", function( data ) { return(data)});

Already got the return on the variable

    
09.03.2018 / 18:47