使用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>