使用JS按类或ID从URL数据中获取内容
Get content from URL data by class or ID using JS
我整晚都在想解决方案,但我想不通。
我有下载URL内容的PHP代码:
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$data = get_data($url);
我想通过类名或ID从div中获取内容,所以我把这个变量发送到JS,如下所示:
<script>
var data = <?php echo json_encode($data); ?>;
alert(data);
//alert shows all code of downloaded URL
//$( ".content" ).html( data );
//this line show whole page but I want only specific element/class
</script>
我怎样才能做到这一点?假设我想从Javascript中的"data"变量中获得class="productMainTitle"的H1标签的内容?
任何小费都将不胜感激!
使用DomParser
var parser = new DomParser();
var doc = parser.parseFromString(data, "text/xml");
然后像往常一样从文档中获取您想要的元素
doc.getElementById("id")
并将其html分配给您的div.
编辑:
$("#content").html(doc.getelementById("col1-755").text());
取决于您想要做什么。
1.只发送HTML客户端的相关片段
看看@artm的回答。
2.发送所有HTML客户端并在那里进行排序
<script>
var $data = $("<?php echo $data; ?>");
$data.find("h1.productMainTitle").appendTo(".content");
</script>
假设json_encode()
是不必要的。如果我错了,请重新插入
如果你只想要"h1.productMainTitle"片段,这比(1)效率低,但如果你想要更多的片段,那么这是一种可行的方法。
使用<iframe>
按URL打开子页面,并在必要时隐藏它们。
现在我们可以不使用URL:创建空的框架并强制在其中写入一些html
逐步尝试以下脚本(按下按钮),看看发生了什么:
<body>
<button onclick="createFrame();">createFrame</button>
<button onclick="getElement();">getElement</button>
<button onclick="closeFrame();">closeFrame</button>
<button onclick="showExtractedElement();">showExtractedElement</button>
<script>
var frame
, frameDoc
, elem
, htmlData = '<html><body><h1 class="myClass">Hello</h1></body></html>'
/*somehow we got this string containing html data*/
function createFrame()
{
frame = document.createElement( "iframe" );
frame.setAttribute( 'hidden', '' ); // on debug remove this line to see the frame
document.body.appendChild( frame );
frame.contentDocument.write(htmlData)
}
function getElement( )
{
elem = frame.contentDocument.querySelector( '.myClass' )
}
function closeFrame()
{
document.body.removeChild( frame );
}
// the extracted element remains
function showExtractedElement()
{
console.log( elem )
}
// call this method from console or script to do all the magic
function doEverything()
{
createFrame()
getElementFromAnotherPage()
closeFrame()
showExtractedElement()
}
</script>
</body>
相关文章:
- 使用jquery将mysql数据获取到新的表行中
- 使用createContainer将Meteor数据获取到React Native中时出现问题
- 创建按钮,根据表单字段中的数据获取特定的URL
- 将JSON API数据获取到html
- 将json数据获取到数组中
- 如何将具有多个标签的多个的所有数据获取到一个数组中
- 将状态的 URL 数据获取到模板中
- 如何在jquery中将xml解析数据获取为全局变量
- 在没有JQuery的情况下将JSON数据获取到TVML项目中
- Angular js如何将索引数据获取到另一个模板中
- 如何将PHP Post数据获取到jquery ajax请求中
- 使用javascript中.data()中存储的数据获取变量
- 无法将动态数据获取到 Jquery 饼图中
- 将节点.js neDB 数据获取到变量中
- 更新页面 JSON 数据获取下拉更改
- 将数据绑定到 kendo 下拉列表时,如何将 ajax 响应数据获取到变量
- 画布图像数据获取的值不超过 102,000 个
- 如何通过 JQuery JSON 数据获取 CheckBox(@Html.CheckBox) 的值
- 从html到jquery再到php,再从php到jquery到html,将数据传递到php文件并将数据获取到php文件中
- 如何将Jquery.get中的数据获取到Javascript中的一个变量中