jQuery load body from external HTML

后端 未结 5 956
南笙
南笙 2020-12-17 09:15

I\'m using jQuery and trying to load the body from an external HTML file.

It works if I try to load some div:

$(\'body\').load(\'example.h

相关标签:
5条回答
  • 2020-12-17 09:39

    I guess what you need is to add an iframe. Pass the URL to its src property. Your whole html will get loaded in this iframe then. A clean and simple solution for your problem. All the best :-)

    0 讨论(0)
  • 2020-12-17 09:40

    When you use load without a selector, it strips the <html>, <head>, and <body> tags, but leaves all of the children of <head> and <body> intact, including title, script, and style tags. However, when you use a selector, it is applied after the body tag is stripped, so it's impossible to match against it.

    Instead, wrap all of your body content inside another tag, and select that tag instead:

    <html><head><title>Hello!</title</head>
    <body>
      <div id="jquery-load-point">
        ... <!-- rest of body content -->
      </div>
    </body>
    </html>
    

    Now, you can load it like this:

    $("#destination").load("http://my.url/to/page #jquery-load-point");
    
    0 讨论(0)
  • 2020-12-17 09:41

    Make sure you are using jQuery 1.5.1 and not 1.5. The load feature in 1.5 had issues. I answered a similar questions at jquery .load() doesn't work

    Another thing is to try it in different browsers to make sure it's not a browser issue. Chrome doesn't allow you to use load when working from localhost without doing some tweaking.

    0 讨论(0)
  • 2020-12-17 09:42

    From http://api.jquery.com/load

    jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

    Reading the above, it seems possible that your browser be only returning the body innerHTML. This obviously should be the same as requesting body, but maybe it's causing an error because body is not found?

    I'd suggest trying a different browser.

    0 讨论(0)
  • 2020-12-17 09:54

    If you want to load the whole body, $('body').load('example.html'); should be enough.

    If not, could you explain why ?

    Anyway, the solution provided by Steve is the right one.

    0 讨论(0)
提交回复
热议问题