简体   繁体   中英

Trying to Load HTML Source Code using JQuery

I am trying to load some HTML source code I have in a text file into jquery. When I click the link to add the text nothing loads into the page. Any suggestions?

Load Script:

<div data-role="collapsible" data-collapsed="true">
    <h3>Accordion Concept</h3>
    <p>The accordion concept splits the page into catagories to save space. Each catagory contains information but this information is collapsed in order to make it so you only see the information you want to see on the page.</p>
    <div id = "loadEx">Click Here to Load Example Script File</div>
    <script>
        $( "#loadEx" ).click(function() {
            $('#hello').load('mywebpage.txt');
        });
    </script>
    <pre id = "hello"></pre>
</div>


Text File:

<body class="container">
    <div data-role="page">
        <div data-role="header">
            <h1> Page  One Title </h1>
        </div>
        <div data-role="content">
            <div data-role="collapsible-set" >
                <div data-role="collapsible" data-collapsed="true">
                    <h3> Header number one </h3>
                    <p> information for header number one is here. </p>
                </div>
                <div data-role="collapsible" data-collapsed="true">
                    <h3> Header number two </h3>
                    <p> information for header number two is here. </p>
                </div>
                <div data-role="collapsible" data-collapsed="true">
                    <h3> Header number three </h3>
                    <p> information for header number three is here. </p>
                </div>
            </div>
            <div data-role="footer">
                Copyright
            </div>   
        </div>

</body>

The real question emerged through the comments:

what would I change in the CSS that would make it so it appears as text rather than HTML?

You wouldn't use CSS for that. You need to not use the load method (which is designed to handle HTML, not text).

Use a less short-handy Ajax function, and manually put the data into the element as text.

        $( "#loadEx" ).click(function() {
            $.get('mywebpage.txt', function (data) {
                $('#hello').text(data);
            });
        });

first load the dom then use $.get function.

$(document).ready(function(){
   $( "#loadEx" ).click(function() {

  $('#hello').html("hey there, I am calling get request");
  $.get('mywebpage.txt',function(data,status){
    if(status == "error"){
        alert("File not found "+status);
    }

    $('#hello').html(data);

  });

 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM