简体   繁体   中英

Javascript/JQuery: innerHTML Not Working

I would like to change the content inside <div id="homePagePosts"> to be the new data from the server. The new data is in HTML format rendered by the server. However, the old HTML still stays the same after the AJAX data has been received by the browser.

When I console.log as shown below, I can see the rendered new HTML data is shown in the console. I have placed both Javascript and JQuery file at the bottom of the <body> but still doesn't work. I'm not too sure where it goes wrong here.

HTML

<div id="homePagePosts">
    <% include ../ajaxSnippets/mainHome %>
</div>

Javascript

$.ajax({
      url: "/main/home",
      type: "POST",
      contentType: "application/json",
      data: JSON.stringify(sendData)
  }).done(function(result){
      //This shows up in the console
      console.log(result)
      updateMainPagePosts(result);
  }).fail(function(err){
      console.log(err);
  });

var updateMainPagePosts = function(posts){
  document.getElementById("homePagePosts").innerHTML = posts;
};

You have defined the function as a variable and is not usable in this method.

change this :

var updateMainPagePosts = function(posts){
  document.getElementById("homePagePosts").innerHTML = posts;
};

to this :

function updateMainPagePosts(posts){
  document.getElementById("homePagePosts").innerHTML = posts;
}

More details from: https://www.quora.com/Is-the-var-x-function-the-same-as-the-function-x-in-JavaScript :

This will break. It uses a Function Expression which is being assigned to a variable. console.log(myFunction(1, 2)); var myFunction = function (a, b) { return a + b; };

This will print '3' to your console. It uses a Function Declaration. console.log(myFunction(1, 2)); function myFunction(a, b) { return a + b; }

The difference is that in the example with a function Definition, the function is being "hoisted" to the start of the scope (which could be a parent function, or the file, for example) by the JavaScript interpreter, which means anywhere within that scope it can be called and it will execute the function you have written.

In the function Expression the function is being passed around as if it were a value and is interpreted whenever it is asked to be. In the example we're seeing here, it, as a value is being assigned to the myFunction variable. Since we put a 'var' statement in front of that variable, then myFunction that variable is being hoisted, but its value, the function expression, is not hoisted (do not get the two confused).

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