Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HTML code using JavaScript with a URL

I am trying to get the source code of HTML by using an XMLHttpRequest with a URL. How can I do that?

I am new to programming and I am not too sure how can I do it without jQuery.

like image 779
simplified Avatar asked Jun 16 '11 16:06

simplified


People also ask

How do I get HTML using Javascript?

Get HTML elements by TagName: In javascript, getElementsByTagName() method is useful to access the HTML elements using the tag name. This method is the same as the getElementsByName method. Here, we are accessing the elements using the tag name instead of using the name of the element.

How do I get HTML to show content from another url?

You could use an <iframe> in order to display an external webpage within your webpage. Just place the url of the webpage that you want to display inside the quotes of the src attribute. Show activity on this post. Either you use an iframe or you load the site via AJAX into a div (e.g. using jQuerys load() method).

How do you reference a url in Javascript?

Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc. The following example will display the current url of the page on click of the button.


1 Answers

Use jQuery:

$.ajax({ url: 'your-url', success: function(data) { alert(data); } }); 

This data is your HTML.

Without jQuery (just JavaScript):

function makeHttpObject() {   try {return new XMLHttpRequest();}   catch (error) {}   try {return new ActiveXObject("Msxml2.XMLHTTP");}   catch (error) {}   try {return new ActiveXObject("Microsoft.XMLHTTP");}   catch (error) {}    throw new Error("Could not create HTTP request object."); }  var request = makeHttpObject(); request.open("GET", "your_url", true); request.send(null); request.onreadystatechange = function() {   if (request.readyState == 4)     alert(request.responseText); }; 
like image 148
Senad Meškin Avatar answered Oct 05 '22 22:10

Senad Meškin