簡體   English   中英

加載多個json文件,並使用ajax和jquery將其顯示為html

[英]Load multiple json files and display it to the html using ajax and jquery

我正在嘗試獲取包含對象的三個不同的json文件,並使用jquery get方法將它們加載到單個頁面中。 我需要抓取對象並使用jquery在頁面中顯示所有三個對象。 我在加載和顯示所有三個文件時遇到了麻煩...感謝您的幫助。 謝謝!

這是代碼:

$(document).ready(function(){
$("button").click(function(){
    $.get("objectone.json", function(data){
        $('#mydiv').html((JSON.stringify(data)));
    });
    $.get("objectwo.json", function(data){
        $('#mydiv').html((JSON.stringify(data)));
    });
    $.get("objectthree.json", function(data){
        $('#mydiv').html((JSON.stringify(data)));
    });
  });
});

和HTML:

<button type="button" name="button">Click Me</button>

<div id="mydiv">

</div>

.html方法將所選元素的所有內容替換為您提供的html內容。 通過在同一元素上使用3次,可以將所有內容替換3次。

將.html替換為.append,這會將新數據添加到所選元素內容的末尾。

代替.html()方法,使用JQuery的.append()

由於您正在使用.html()因此只要您調用它,它將用新內容替換以前的內容,而使用.append() ,它將添加到現有內容中。

在這里閱讀更多

 $(document).ready(function() { var url = "https://rawgit.com/typicode/json-server/master/routes.json"; $("button").click(function() { $.get(url, function(data) { $('#mydiv').append((JSON.stringify(data))); }); $.get(url, function(data) { $('#mydiv').append((JSON.stringify(data))); }); $.get(url, function(data) { $('#mydiv').append((JSON.stringify(data))); }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="button" name="button">Click Me</button> <div id="mydiv"> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM