简体   繁体   中英

json & JavaScript replacing html h1 heading?

When I reload my browser to show some json data the JavaScript code keeps replacing my HTML code? How can I correct the problem?

JavaScript code:

$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data)  {
      document.write(data.title);
};

HTML Code:

<div class="container">
    <div id="json_example">
    <h1>json Example</h1>
   </div>
</div>

Don't use document.write() as it replaces fully built HTML documents with the new content. document.write() should only ever be used to construct dynamic pages while the page is being built.

Instead, just populate some pre-existing element with data.title ,

As in:

$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data)  {
      $("#output").text(data.title);
};

<div class="container">
    <div id="json_example">
    <h1>json Example</h1>
    <span id="output"></span>
   </div>
</div>

You are using document.write() which takes your document, and replaces it's content with the content you supply to the function. If you want to replace just the content of the <div id="json_example"></div> element, then you can use the following snippet in place of the document.write() :

$("#json_example").text(data.title);

For non jQuery-version:

document.querySelector("#json_example").innerText = data.title;

If you want to replace the content of the <h1> the correct selector would be #json_example h1 instead.

In all the snippets what you do is find the element you want to change the content of using a CSS-selector. Both jQuery and pure Javascript supports this since IE8.

After finding the correct element, you set the elements content text to the content you want.

NOTE! Do NOT use innerHtml or .html() to set the content, as that opens you to script injections. Only use those methods when you generate the HTML yourself on the fly, in the browser. Even your database needs to be considered dirty.

try this

$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data)  {
      document.getElementById("json_example").textContent = data.title;
};

Since you're already using jQuery here's a possible solution which uses it.

$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data)  {
  $("#json_example").html("<h1>" + data.title + "</h1>");
};

This replaces your div html with your content.

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