如何使用javascript或jQuery解析html内容 [英] How to parse html content using javascript or jQuery

查看:76
本文介绍了如何使用javascript或jQuery解析html内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来解析HTML内容使用JavaScript?

我有一个要求只显示从其他网站到我的网站的div。那可能吗?例如,我想在我的网站中只显示 div#leftcolumn w3schools.com 。这甚至有可能吗?



如何使用javascript或jQuery执行相同的操作?



p>

解决方案

您需要查看同源策略


在计算中,相同的源策略
是一个重要的安全概念为
数量的浏览器端编程
语言,如JavaScript。
策略允许在
页面上运行的脚本来自同一站点
,以访问彼此的方法和
属性,但不具有特定的
限制,但可阻止访问





$ b $您可以获取数据,它拥有大多数方法和属性为:

相同协议和主机

您需要实现 JSONP 解决它。



< hr>

尽管在相同的协议和主机上,jQuery的 load() 函数,你可以这样使用:

  $( '(#foo')。load('somepage.html div#leftcolumn',function(){
// loaded
});






另一个可能的解决方案是(未经测试)服务器端语言,你不需要 jsonp 。下面是一个PHP示例。



<1>创建一个名为 ajax.php 的php页面,它:

 <?php 
$ content = file_get_contents(http://w3schools.com);
echo $ content? $ content:'0';
?>

2)在某个页面上,输入以下代码:
$ b $如果(数据!=='0')加载('ajax.php div#leftcolumn',函数(数据){
> $('#yourDiv' ){/ *已加载* /}
});

请确保:


  • 你指定正确的路径到 ajax.php 文件

  • 你有 allow_url_fopen php.ini。
  • 您需要 c> yourDiv id 将收到的内容放入

Is there a way to parse html content using javascript?

I have a requirement to display only a div from some other site into my site. Is that possible? For example consider I want to show only div#leftcolumn of w3schools.com in my site. Is this even possible?

How can I do the same using javascript or jQuery?

Thanks.

解决方案

You need to have a look at Same Origin Policy:

In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.

For you to be able to get data, it has to be:

Same protocol and host

You need to implement JSONP to workaround it.


Though on same protocol and host, jQuery has load() function which you would use like this:

$('#foo').load('somepage.html div#leftcolumn', function(){
  // loaded
}); 


Another possible solution (untested) would be to use server-side language and you don't need jsonp. Here is an example with PHP.

1) Create a php page named ajax.php and put following code in it:

<?php
  $content = file_get_contents("http://w3schools.com");
  echo $content ? $content : '0'; 
?>

2) On some page, put this code:

$('#yourDiv').load('ajax.php div#leftcolumn', function(data){
    if (data !== '0') { /* loaded */ }
}); 

Make sure that:

  • you specify correct path to ajax.php file
  • you have allow_url_fopen turned on from php.ini.
  • your replace yourDiv with id of element you want to put the received content in

这篇关于如何使用javascript或jQuery解析html内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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