jquery - How to get HTML source with JavaScript? -


i trying html source javascript:

why not work?:

<!doctype html> <html> <head>   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>   <script>     function mygethtml()       {         $.get("www.example.com/test1.html", function(data){           return data;         });       }   </script> </head>  <body>   test 30.9.2015   <script>     alert(mygethtml());   </script> </body> </html> 

(below, i'm assuming need content filen in source, from same origin of page.)

your code doen't works because the return of mygethtml method request itself, , success callback of request returns data.

you do:

function mygethtml(){     $.get("www.example.com/test1.html", function(data){       //alert(data);       //or use console.log() instead.       console.log(data);     });   } 

and then

mygethtml(); //this log data after succesfull request. 

further reading: https://api.jquery.com/jquery.get/

hint on use case:

a simple tutorial from tuts+ on making simple ajax requests.

with pure js:

load('test.html', function(xhr) {     document.getelementbyid('container').innerhtml = xhr.responsetext; });  function load(url, callback) {         var xhr;          if(typeof xmlhttprequest !== 'undefined') xhr = new xmlhttprequest();         else {             var versions = ["msxml2.xmlhttp.5.0",                              "msxml2.xmlhttp.4.0",                             "msxml2.xmlhttp.3.0",                              "msxml2.xmlhttp.2.0",                             "microsoft.xmlhttp"]               for(var = 0, len = versions.length; < len; i++) {                 try {                     xhr = new activexobject(versions[i]);                     break;                 }                 catch(e){}              } // end         }          xhr.onreadystatechange = ensurereadiness;          function ensurereadiness() {             if(xhr.readystate < 4) {                 return;             }              if(xhr.status !== 200) {                 return;             }              //               if(xhr.readystate === 4) {                 callback(xhr);             }                    }          xhr.open('get', url, true);         xhr.send('');     } 

or jquery library

$('#container').load('test.html'); 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -