繁体   English   中英

Jquery 从 html 拉取 json 数据

[英]Jquery pull json data from html

我通过 NodeJS Express 将数据添加到 html,并使用 .setHeader,我得到了 html 标题为 json。从 html 中的 JS 文件中提取数据并将其发送到另一个 html 文件,仅作为每个标题的标题。

有 JavaScript 代码,


$(document).ready(function () {
    $.get("/admin/getposts", null, function (data) {

       // Main bir div oluşturmak
        $(".postsMain").html("");

        $.each(data, function (i, item) {
          
        // Div 2 için html ayarlamak
        var html += "<div class='postsAlt'>";
            html += "<p>" + i.title + "</p>"
            html += "</div>";

            // Div 2'leri div1 lere aktarmak
            $(".postsMain").append(html);
        });

    }, "json").done(function() {
      console.log('Başarıyla data çekildi') 
    }) 
});

NodeJS中有拉取数据

app.get("/admin/getposts", (req, res) => {
  let titles = [];
  Object.entries(postData.all()).forEach((entry) => {
    const [ID, data] = entry;
    titles.push(data.data)
  });


  res.setHeader('Content-Type', 'application/json')
  res.send(JSON.stringify(titles));
});

对您的代码进行一些更正。

$(function () {
  $.getJSON("/admin/getposts", function (data) {
    $(".postsMain").empty();
    $.each(data, function (i, item) {
      var alt = $("<div>", {
        class: "postsAlt"
      }).appendTo(".postsMain");
      $("<p>").html(item.title).appendTo(alt);
      console.log('Başarıyla data çekildi'); 
    });
  });
});

在 Each 循环中,您使用i作为索引,使用item作为值。 所以i.item应该抛出一个关于未定义的错误。 我将其切换为item.title ,它应该提供适当的详细信息。

我还更新了代码以使用 jQuery 创建新的 HTML 元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM