У меня есть несколько кнопок навигации и область содержимого для содержимого. Я не мог вытащить данные из файла .JSON в свою область содержимого HTML без обновления всей страницы. Я просто хочу обновить свою область контента, когда нажимаю на определенные кнопки навигации

Я пытался использовать AJAX, но это не сработало. Поскольку мои знания в JSON и AJAX невелики, и я провел некоторые поиски того, как я могу это сделать, но он просто не смог обновить область содержимого.

HTML-файл

{amp}lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"{amp}gt; {amp}lt;html xmlns="http://www.w3.org/1999/xhtml"{amp}gt;{amp}lt;head{amp}gt; {amp}lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /{amp}gt;{amp}lt;title{amp}gt;A simple AJAX website with jQuery{amp}lt;/title{amp}gt; {amp}lt;link rel="stylesheet" type="text/css" href="demo.css" /{amp}gt; {amp}lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;script type="text/javascript" src="script.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;/head{amp}gt; {amp}lt;body{amp}gt; {amp}lt;div id="rounded"{amp}gt; {amp}lt;img src="img/top_bg.gif" alt="top" /{amp}gt; {amp}lt;div id="main" class="container"{amp}gt; {amp}lt;h1{amp}gt;A simple AJAX driven jQuery website{amp}lt;/h1{amp}gt; {amp}lt;h2{amp}gt;Because simpler is better{amp}lt;/h2{amp}gt; {amp}lt;ul id="navigation"{amp}gt; {amp}lt;li{amp}gt;{amp}lt;a href="#page_1"{amp}gt;Page 1{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;li{amp}gt;{amp}lt;a href="#page_2"{amp}gt;Page 2{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;li{amp}gt;{amp}lt;a href="#page_3"{amp}gt;Page 3{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;li{amp}gt;{amp}lt;a href="#page_4"{amp}gt;Page 4{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;li{amp}gt;{amp}lt;a href="#products"{amp}gt;Products{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;li{amp}gt;{amp}lt;img id="loading" src="img/ajax_load.gif" alt="loading" /{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;br{amp}gt;{amp}lt;br{amp}gt;{amp}lt;br{amp}gt; {amp}lt;li id="des1"{amp}gt;{amp}lt;a href="#mushroom"{amp}gt;Mushroom{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;li id="des2"{amp}gt;{amp}lt;a href="#potato"{amp}gt;Potato{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;li id="des3"{amp}gt;{amp}lt;a href="#carrot"{amp}gt;Carrot{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;li id="des4"{amp}gt;{amp}lt;a href="#tomato"{amp}gt;Tomato{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;/ul{amp}gt; {amp}lt;div class="clear"{amp}gt;{amp}lt;/div{amp}gt; {amp}lt;div id="dvProdList"{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div class="clear"{amp}gt;{amp}lt;/div{amp}gt; {amp}lt;div id="pageContent"{amp}gt; Hello, this is a demo for The Rich Internet Application Case Study{amp}lt;a href="http://www.lithan.com" target="_blank"{amp}gt;Lithan{amp}lt;/a{amp}gt;. To test it, click some of the buttons above. Have a nice stay!{amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div class="clear"{amp}gt;{amp}lt;/div{amp}gt; {amp}lt;img src="img/bottom_bg.gif" alt="bottom" /{amp}gt;{amp}lt;/div{amp}gt; {amp}lt;div class="demo" align="center"{amp}gt; this is a {amp}lt;a href="http://lithan.com/" target="_blank"{amp}gt;Lithan{amp}lt;/a{amp}gt; demo{amp}lt;/div{amp}gt; {amp}lt;/body{amp}gt; {amp}lt;/html{amp}gt; 

Файл script.js

 var default_content=""; $(document).ready(function(){ checkURL(); $('ul li a').click(function (e){ checkURL(this.hash); }); //filling in the default content default_content = $('#pageContent').html(); setInterval("checkURL()",250); }); var lasturl=""; function checkURL(hash) { if(!hash) hash=window.location.hash; if(hash != lasturl) { lasturl=hash; // FIX - if we've used the history buttons to return to the homepage, // fill the pageContent with the default_content if(hash=="") $('#pageContent').html(default_content); else{ if(hash=="#products") loadProducts(); else loadPage(hash); } } } function loadPage(url) { url=url.replace('#',''); $('#loading').css('visibility','visible'); $.ajax({ type: "POST", url: "load_page.jsp", data: 'page=' url, dataType: "html", success: function(msg){ if(parseInt(msg)!=0) { $('#pageContent').html(msg); $('#loading').css('visibility','hidden'); } } }); } function loadProducts() { $('#loading').css('visibility','visible'); var jsonURL = "products.json"; $.getJSON(jsonURL, function (json) { var imgList= "{amp}lt;ul class="products"{amp}gt;"; $.each(json.products, function () { imgList  = '{amp}lt;li{amp}gt;{amp}lt;img src= "'   this.imgPath   '"{amp}gt;{amp}lt;h3{amp}gt;'   this.name   '{amp}lt;/h3{amp}gt;{amp}lt;/li{amp}gt;'; }); imgList ='{amp}lt;/ul{amp}gt;' $('#pageContent').html(imgList); $('#loading').css('visibility','hidden'); }); } 

Файл .JSON

 { "productDes": [{ "title": "Mushrooms", "details": "A mushroom, or toadstool, is the fleshy, spore-bearing fruiting body of a fungus, typically produced above ground on soil or on its food source.", "price": "1kg = SGD20" }, { "title": "Potato", "details": "The potato is a starchy, tuberous crop from the perennial nightshade Solanum tuberosum, native to the Americas. In many contexts, potato refers to the edible tuber, but it can also refer to the plant itself. Common or slang terms include tater, tattie and spud.", "price": "1kg = SGD7" }, { "title": "Carrot", "details": "The carrot is a root vegetable, usually orange in colour, though purple, black, red, white, and yellow cultivars exist. Carrots are a domesticated form of the wild carrot, Daucus carota, native to Europe and southwestern Asia.", "price": "1kg = SGD4" }, { "title": "Tomato", "details": "The tomato is the edible, often red, berry of the plant Solanum lycopersicum, commonly known as a tomato plant. The species originated in western South America. The Nahuatl word tomatl gave rise to the Spanish word tomate, from which the English word tomato derived.", "price": "1kg = SGD5" } ] } 

Я хочу изменить существующее содержимое в моей области содержимого только тогда, когда кнопки навигации и вся страница не обновляются, тогда как только область содержимого обновляется до содержимого заголовка, описания, цены и изображения рядом с содержимым.

Я не знаю, какие элементы HTML вы используете, когда говорите о «кнопках навигации и области содержимого для содержимого», но это не имеет большого значения, так как все, что вы хотите сделать, это загрузить данные в некоторые элементы HTML.

В этом примере используется функция formatUnicorn с шаблонами, ajax и вашим файлом json, а функция fucntion создает элемент html для каждого элемента json вашего массива productDes, используя простой цикл:

Содержание HTML:

 {amp}lt;head{amp}gt; {amp}lt;meta charset="utf-8"{amp}gt; {amp}lt;title{amp}gt;{amp}lt;/title{amp}gt; {amp}lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"{amp}gt; {amp}lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;/head{amp}gt; {amp}lt;body{amp}gt; {amp}lt;script type="text/template" id="listTemplate"{amp}gt; {amp}lt;li {amp}gt;{amp}lt;a data-toggle="tab" href="#{title}"{amp}gt;{title}{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;/script{amp}gt; {amp}lt;script type="text/template" id="divTemplate"{amp}gt; {amp}lt;div id="{title}" class="tab-pane fade"{amp}gt; {amp}lt;h3{amp}gt;{title}{amp}lt;/h3{amp}gt; {amp}lt;p{amp}gt;{details}{amp}lt;/p{amp}gt; {amp}lt;br{amp}gt; {amp}lt;p{amp}gt;Price: {price}{amp}lt;/p{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/script{amp}gt; {amp}lt;div class="container"{amp}gt; {amp}lt;h2{amp}gt;Navigation with Tabs{amp}lt;/h2{amp}gt; {amp}lt;p{amp}gt;Example to fill json content in tabs{amp}lt;/p{amp}gt; {amp}lt;ul class="nav nav-tabs" id="listOfItems"{amp}gt; {amp}lt;li class="active"{amp}gt;{amp}lt;a data-toggle="tab" href="#home"{amp}gt;Home{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;/ul{amp}gt; {amp}lt;div class="tab-content" id="listOfDivs"{amp}gt; {amp}lt;div id="home" class="tab-pane fade in active"{amp}gt; {amp}lt;h3{amp}gt;HOME{amp}lt;/h3{amp}gt; {amp}lt;p{amp}gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.{amp}lt;/p{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/body{amp}gt; 

Сценарий :

 String.prototype.formatUnicorn = function () { "use strict"; var str = this.toString(); if (arguments.length) { var t = typeof arguments[0]; var key; var args = ("string" === t || "number" === t) ? Array.prototype.slice.call(arguments) : arguments[0]; for (key in args) { str = str.replace(new RegExp("\{"   key   "\}", "gi"), (Array.isArray(args[key]) ? JSON.stringify(args[key]) : args[key])); } } return str; }; // this function replaces the {} elements with the value of and array element that have the same key name function _ajax(){ return $.ajax({ url: 'products.json', type: 'GET', dataType: 'JSON' }) } //a simple ajax function to get the productDes array from the products.json file //once you call the function and get the response with the deferred done you loop through the array //and fill the template with the element that match the key, after that you append the element to your container _ajax(). done((response)={amp}gt;{ let lisItemTemplate = $('#listTemplate').html(), divItemTemplate = $('#divTemplate').html(); console.log(response); if (response.productDes.length {amp}gt; 0) { $.each(response.productDes,function(index, el) { var listItem = lisItemTemplate.formatUnicorn(el); var divItem = divItemTemplate.formatUnicorn(el); $('#listOfItems').append(listItem); $('#listOfDivs').append(divItem); }); } }) 

Наконец, вот фрагмент без ajax, использующий только массив products:

 String.prototype.formatUnicorn = function() { "use strict"; var str = this.toString(); if (arguments.length) { var t = typeof arguments[0]; var key; var args = ("string" === t || "number" === t) ? Array.prototype.slice.call(arguments) : arguments[0]; for (key in args) { str = str.replace(new RegExp("\{"   key   "\}", "gi"), (Array.isArray(args[key]) ? JSON.stringify(args[key]) : args[key])); } } return str; }; let products = { "productDes": [{ "title": "Mushrooms", "details": "A mushroom, or toadstool, is the fleshy, spore-bearing fruiting body of a fungus, typically produced above ground on soil or on its food source.", "price": "1kg = SGD20" }, { "title": "Potato", "details": "The potato is a starchy, tuberous crop from the perennial nightshade Solanum tuberosum, native to the Americas. In many contexts, potato refers to the edible tuber, but it can also refer to the plant itself. Common or slang terms include tater, tattie and spud.", "price": "1kg = SGD7" }, { "title": "Carrot", "details": "The carrot is a root vegetable, usually orange in colour, though purple, black, red, white, and yellow cultivars exist. Carrots are a domesticated form of the wild carrot, Daucus carota, native to Europe and southwestern Asia.", "price": "1kg = SGD4" }, { "title": "Tomato", "details": "The tomato is the edible, often red, berry of the plant Solanum lycopersicum, commonly known as a tomato plant. The species originated in western South America. The Nahuatl word tomatl gave rise to the Spanish word tomate, from which the English word tomato derived.", "price": "1kg = SGD5" } ] }; let lisItemTemplate = $('#listTemplate').html(), divItemTemplate = $('#divTemplate').html(); if (products.productDes.length {amp}gt; 0) { $.each(products.productDes, function(index, el) { var listItem = lisItemTemplate.formatUnicorn(el); var divItem = divItemTemplate.formatUnicorn(el); $('#listOfItems').append(listItem); $('#listOfDivs').append(divItem); }); } 
  {amp}lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"{amp}gt; {amp}lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;body{amp}gt; {amp}lt;script type="text/template" id="listTemplate"{amp}gt; {amp}lt;li{amp}gt;{amp}lt;a data-toggle="tab" href="#{title}"{amp}gt;{title}{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;/script{amp}gt; {amp}lt;script type="text/template" id="divTemplate"{amp}gt; {amp}lt;div id="{title}" class="tab-pane fade"{amp}gt; {amp}lt;h3{amp}gt;{title}{amp}lt;/h3{amp}gt; {amp}lt;p{amp}gt;{details}{amp}lt;/p{amp}gt; {amp}lt;br{amp}gt; {amp}lt;p{amp}gt;Price: {price}{amp}lt;/p{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/script{amp}gt; {amp}lt;div class="container"{amp}gt; {amp}lt;h2{amp}gt;Navigation with Tabs{amp}lt;/h2{amp}gt; {amp}lt;p{amp}gt;Example to fill json content in tabs{amp}lt;/p{amp}gt; {amp}lt;ul class="nav nav-tabs" id="listOfItems"{amp}gt; {amp}lt;li class="active"{amp}gt;{amp}lt;a data-toggle="tab" href="#home"{amp}gt;Home{amp}lt;/a{amp}gt;{amp}lt;/li{amp}gt; {amp}lt;/ul{amp}gt; {amp}lt;div class="tab-content" id="listOfDivs"{amp}gt; {amp}lt;div id="home" class="tab-pane fade in active"{amp}gt; {amp}lt;h3{amp}gt;HOME{amp}lt;/h3{amp}gt; {amp}lt;p{amp}gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.{amp}lt;/p{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/body{amp}gt; 

Надеюсь, это поможет