使用带有 URL 的 JavaScript 获取 HTML 代码 [英] Get HTML code using JavaScript with a URL

查看:41
本文介绍了使用带有 URL 的 JavaScript 获取 HTML 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用带有 URL 的 XMLHttpRequest 来获取 HTML 的源代码.我该怎么做?

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

我是编程新手,我不太确定没有 jQuery 怎么办.

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

推荐答案

使用 jQuery:

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

此数据是您的 HTML.

This data is your HTML.

没有 jQuery(只有 JavaScript):

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

这篇关于使用带有 URL 的 JavaScript 获取 HTML 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆