Get HTML code using JavaScript with a URL

前端 未结 5 1350
鱼传尺愫
鱼传尺愫 2020-12-01 14:31

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 wit

5条回答
  •  [愿得一人]
    2020-12-01 14:42

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

提交回复
热议问题