加载另一个页面's的HTML,并使用jQuery通过选择器对其进行解析

Load another page's HTML and parse it through selectors with jQuery

本文关键字:选择器 jQuery 另一个 HTML 加载      更新时间:2023-09-26

我在jsFiddle 上试过一个例子

$.get('/user/login/', function(content){  /* (jsFiddle.net/user/login is in the same domain) */
    alert($('*',content).html()); 
});

但它返回

<a href="/">JSFiddle</a> 

我做错了什么?例如,我想获取HTML的标题,但$('title',content)不起作用

据我所知,JSFiddle不允许AJAX调用。

编辑:但他们确实提供了某种模拟,尽管我没有使用过http://doc.jsfiddle.net/use/echo.html

在没有Ajax的情况下可以做到这一点。

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Load remote content into object element</title>
  </head>
  <body>
    <div id="siteloader"></div>​
    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script>
      $("#siteloader").html('<object data="http://tired.com/">');
    </script>
  </body>
</html>

获取页面后,尝试对其进行解析。

它将检查jsfiddles登录页面。类似的东西

http://jsfiddle.net/user/login/

您可以使用类似/echo/json/的内容作为url:

<div class='wrapper'>
<p>JSON will be received in 3 seconds</p>
<ul id='post'></ul>
</div>
new Request.JSON({
    url: '/echo/json/',
    data: {
        json: JSON.encode({
            text: 'some text',
            array: [1, 2, 'three'],
            object: {
                par1: 'another text',
                par2: [3, 2, 'one'],
                par3: {}
            }
        }),
        delay: 3
    },
    onSuccess: function(response) {
        show_response(response, $('post'));
    }
}).send();
show_response = function(obj, result) {
    $H(obj).each(function(v, k) {
        new Element('li', {
            text: k + ': ' + v
        }).inject(result);
    });
    result.highlight();
};

jsfiddle演示:http://jsfiddle.net/zalun/QsHw4/#