JQuery + AJAX动态div内容

I'm trying to create a dynamic web page to show some content and change it without reloading the full page but some part of it.

When i press a button of my navigation bar it calls a JavaScript function to change the content of my div tag

<div class="row text-left" id="center"></div>

with this code i put into my div class some text

$('#navHome').click(function(){
    $('#center').html("this is my home");
});

Now i want store a content of every section to reload this every time when i press the button. Something like this:

$('#navHome').click(function() {
   $.get('home.txt', function(data) {
      $("#center").html(data);
   }, 'text');
});

in the home.txt i have store my html code of home section but i have no idea how to make this.

Try:

Remove 'text' which you added in last of ajax

$('#navHome').click(function(){
   $.get('home.txt', function(data) {
      alert(data);
      //process text file line by line
      $('#center').html(data);
   });
});

I will try to give you an answer, first at all sorry for my poor english.

My first recommendation for your case is to use AngularJS or any similar framework it´s designed to create SPA(Simple Page Application) which basically means what you want, load te full page one time and only change some part of the page when the user request it. It also has a lot of features that will help you to code faster and cleaner.

Now, I'm going to write some piece of code on simple jquery if you dont want to learn angular now :)

function includeURL(idObj,url){
   var r=$.Deferred();  
   $(document).ready(function() {
      $(idObj).load(url, function() {
          return r.resolve();
      });
   });
}

I use this function to load parts of code, idObj is the div where you want to load the content and url the path of the content. An example could be:

includeURL('#myDiv','html/path/to/content.html');

Try it and tell me if you have any problem.

Hope it helps!

Assuming the contents of the home.txt file can just be placed directly into the <div /> element (i.e. it's just plain text or HTML), have a look at the .load() function within jQuery

$('#center').load('home.txt', function() {
  // This function is called when the contents are loaded successfully
});

So your click handler would look something like this:

$('#navHome').click(function() {
    $('#center').load('home.txt');
});

Make sure that home.txt is in the correct directory. The 'networking' tab available in the developer tools for all good web browsers will help you debug problems if the contents doesn't load correctly

try use the following code:

 
$.ajax({
  url: "home.txt",
  dataType: "text"
})
  .done(function( data ) {
    $("#center").replaceWith(data);
  });

To replace all div content, use replaceWith(data) method
To Append div content apply append(data) method;
You'll get the same result using $get method, but must to assign the dataType as 'text';