get html code using javascript with a url

2019-01-12 03:07发布

I am trying to get the source code of html by using a xmlhttprequest with a url. Is there anyone who can help me with this? I am new to programming and I am not too sure how can I do it without jQuery. Thanks in advance.

3条回答
萌系小妹纸
2楼-- · 2019-01-12 03:31

Use jQuery:

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

This data is your HTML.

Without jQuery (just JS):

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);
};
查看更多
3楼-- · 2019-01-12 03:31

There is a tutorial on how to use ajax here: http://www.w3schools.com/ajax/default.asp

This is an example code taken from that tutorial:

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>
查看更多
贼婆χ
4楼-- · 2019-01-12 03:31

For external (cross-site) solution, you can use: https://stackoverflow.com/a/18447625/2657601

It uses $.ajax() function, so it includes google jquery.

查看更多
登录 后发表回答