Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can get HTML file format as string in javascript

I would like to get in javascript the string value of all the content of an html file like:

<script>
  var HTMLString = getFile("MyPage.html") //some way to get file as HTML string
</script>

Is there any way to do that ?

like image 745
Tamsamani Avatar asked Jan 30 '26 06:01

Tamsamani


2 Answers

Try looking into AJAX. Good for implementing HTML and C# into Javascript/web applications.

In your JS file:

$.ajax({
    type: 'GET',
    url: '/mypage.html',
    success: function (file_html) {
        // success
        alert('success : ' + file_html);
    }
});
like image 194
programnub112 Avatar answered Jan 31 '26 18:01

programnub112


As you want to get the file, you could use $.get from jQuery:

$.get("/MyPage.html", "", function(data){
  alert('success : ' + data);
  });

Just a word of advice: you can only get from the same domain due to the same origin policy.

The main problem is that the request is done asyncronously. This means that the script won't stop, so you don't know at what point the data will be available. This is a change of concept if you come from other static languages, you should pass the function that you want to execute as a callback to jQuery.

like image 23
Francisco Presencia Avatar answered Jan 31 '26 19:01

Francisco Presencia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!