使用JS从类或ID获取URL数据的内容

时间:2014-10-04 11:01:35

标签: javascript php jquery css curl

我整晚都在考虑解决方案,但我无法弄明白。

我有下载网址内容的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>

我怎样才能做到这一点?让我们说我想获得带有class =&#34; productMainTitle&#34;的H1标签的内容。来自&#34;数据&#34; Javascript中的变量?

任何提示都将不胜感激!

3 个答案:

答案 0 :(得分:2)

使用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 :(得分:1)

完全取决于你想做什么。

<强> 1。仅发送HTML客户端的相关片段

请参阅@ artm的答案。

<强> 2。发送所有HTML客户端并将其排序

<script>
    var $data = $("<?php echo $data; ?>");
    $data.find("h1.productMainTitle").appendTo(".content");
</script>

假设json_encode()是不必要的。如果我错了,请重新插入。

如果你只想要&#34; h1.productMainTitle&#34;片段这比(1)效率低,但如果你想要更多片段,那么这是一种可行的方法。

答案 2 :(得分:0)

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