【问题标题】:Changing HTML Content to Json Content将 HTML 内容更改为 Json 内容
【发布时间】:2019-06-20 14:16:50
【问题描述】:

我有几个导航按钮和一个内容区域。 如果不刷新整个页面,我无法将数据从 .JSON 文件拉到我的 HTML 内容区域。 当我点击某些导航按钮时,我只想更新我的内容区域

我尝试使用 AJAX,但它不起作用。由于我对 JSON 和 AJAX 的了解并不多,所以我搜索了一些关于如何做到这一点的信息,但它就是无法更新内容区域。

HTML 文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>A simple AJAX website with jQuery</title>

<link rel="stylesheet" type="text/css" href="demo.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>




<body>
<div id="rounded">
<img src="img/top_bg.gif" alt="top" />
<div id="main" class="container">
<h1>A simple AJAX driven jQuery website</h1>
<h2>Because simpler is better</h2>
<ul id="navigation">
<li><a href="#page_1">Page 1</a></li>
<li><a href="#page_2">Page 2</a></li>
<li><a href="#page_3">Page 3</a></li>
<li><a href="#page_4">Page 4</a></li>
<li><a href="#products">Products</a></li>

<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
<br><br><br>
<li id="des1"><a href="#mushroom">Mushroom</a></li>
<li id="des2"><a href="#potato">Potato</a></li>
<li id="des3"><a href="#carrot">Carrot</a></li>
<li id="des4"><a href="#tomato">Tomato</a></li>
</ul>
<div class="clear"></div>
<div id="dvProdList"> </div>
<div class="clear"></div>
<div id="pageContent"> Hello, this is a demo for The Rich
Internet Application Case Study<a href="http://www.lithan.com" target="_blank">Lithan</a>. To test it,
click some of the buttons above. Have a nice stay!</div>
</div>


<div class="clear"></div>
<img src="img/bottom_bg.gif" alt="bottom" /></div>
<div class="demo" align="center">
this is a <a href="http://lithan.com/" target="_blank">Lithan</a>
demo</div>
</body>
</html>

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= "<ul class=\"products\">";
    $.each(json.products, function () {
      imgList += '<li><img src= "' + this.imgPath + '"><h3>' + this.name + '</h3></li>';
    });
    imgList+='</ul>'
   $('#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"

    }
 ]
}

我只想在导航按钮和整个页面未刷新时更改内容区域上的现有内容,而只有内容区域更新为标题、描述、价格和内容旁边的图像的内容。

【问题讨论】:

  • 我将在几分钟后发布一个示例,它会有所帮助 =)
  • 您在使用 ajax 时走在了正确的轨道上。您需要具体告诉我们您在使用 ajax 时遇到了什么问题才能获得帮助。你已经尝试过什么,失败了怎么办?
  • 有没有办法在这里张贴图片?因为我有一些图像可以告诉我我想做什么。

标签: jquery html json ajax


【解决方案1】:

当您谈论“导航按钮和内容的内容区域”时,我不知道您使用的是哪种 html 元素,但这并不重要,因为您要做的只是将数据加载到某些 html 元素中。

此示例使用带有模板、ajax 和您的 json 文件的 formatUnicorn 函数,该函数使用一个简单的循环为您的 productDes 数组的每个 json 元素创建一个 html 元素:

HTML 内容:

<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
    <script type="text/template" id="listTemplate">
        <li ><a data-toggle="tab" href="#{title}">{title}</a></li>
    </script>
    <script type="text/template" id="divTemplate">
        <div id="{title}" class="tab-pane fade">
            <h3>{title}</h3>
            <p>{details}</p>
            <br>
            <p>Price: {price}</p>
        </div>
    </script>
    <div class="container">
        <h2>Navigation with Tabs</h2>
        <p>Example to fill json content in tabs</p>

        <ul class="nav nav-tabs" id="listOfItems">
            <li class="active"><a data-toggle="tab" href="#home">Home</a></li>
        </ul>

        <div class="tab-content" id="listOfDivs">
            <div id="home" class="tab-pane fade in active">
                <h3>HOME</h3>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
            </div>
        </div>
    </div>
</body>

脚本:

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)=>{
     let lisItemTemplate = $('#listTemplate').html(),
     divItemTemplate = $('#divTemplate').html();

     console.log(response);
    if (response.productDes.length > 0) {
        $.each(response.productDes,function(index, el) {
            var listItem = lisItemTemplate.formatUnicorn(el);
            var divItem = divItemTemplate.formatUnicorn(el);
            $('#listOfItems').append(listItem);
            $('#listOfDivs').append(divItem);
        });
    }
 })

最后这里是没有 ajax 的 sn-p,只使用 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 > 0) {
  $.each(products.productDes, function(index, el) {
    var listItem = lisItemTemplate.formatUnicorn(el);
    var divItem = divItemTemplate.formatUnicorn(el);
    $('#listOfItems').append(listItem);
    $('#listOfDivs').append(divItem);
  });
}
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>


<body>
  <script type="text/template" id="listTemplate">
    <li><a data-toggle="tab" href="#{title}">{title}</a></li>
  </script>
  <script type="text/template" id="divTemplate">
    <div id="{title}" class="tab-pane fade">
      <h3>{title}</h3>
      <p>{details}</p>
      <br>
      <p>Price: {price}</p>
    </div>
  </script>
  <div class="container">
    <h2>Navigation with Tabs</h2>
    <p>Example to fill json content in tabs</p>

    <ul class="nav nav-tabs" id="listOfItems">
      <li class="active"><a data-toggle="tab" href="#home">Home</a></li>
    </ul>

    <div class="tab-content" id="listOfDivs">
      <div id="home" class="tab-pane fade in active">
        <h3>HOME</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
      </div>
    </div>
  </div>
</body>

希望对你有帮助

【讨论】:

  • 是的,这就是我想要弄清楚的。但是我添加的新代码可以做到吗?
  • @NewToThisOutblast 当然只是替换 div 的内容而不是 append mutliple divs
猜你喜欢
  • 2011-08-04
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2019-11-20
  • 1970-01-01
  • 2012-10-20
  • 2013-04-23
  • 1970-01-01
相关资源
最近更新 更多