Get an html and store in variable

Asked

Viewed 242 times

1

I have a simple html file and want to ghettarda it in a variable to use, I made the get so:

 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);

However 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>

data has my html, but not popup, I’m doing something wrong?

  • I’m not sure, but I think your problem is Let. Maybe it doesn’t allow you to set the value in the context below. You may be understanding that the popup is a new variable

  • Or also, if the request is asynchronous, this behavior is normal. Understand that the value assignment, in this case, can occur after the console.log

  • This console.log that you showed in the question is the console.log("data"+data); or console.log("popup"+popup);?

  • the 2, the popup came before

  • It is because the ajax is asynchronous... the popupwill only receive the value within the get function

  • I get it, you can’t make this signature ?

Show 1 more comment

2 answers

4


You are calling a function asynchronous ($.get) and wanting to attribute the return to the variable popup before it returns some value. You could use the method $.ajax with the parameter async: false, but is not recommended due to 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

});

-2

popup = $.get( "popup.html", function( data ) { return(data)});

Already takes the return on the variable

Browser other questions tagged

You are not signed in. Login or sign up in order to post.