简体   繁体   English

Jquery 从 html 拉取 json 数据

[英]Jquery pull json data from html

I added a data to html via NodeJS Express, and with.setHeader, I got the html title as json. Pull data from html in JS file and send it to another html file only as title for each title.我通过 NodeJS Express 将数据添加到 html,并使用 .setHeader,我得到了 html 标题为 json。从 html 中的 JS 文件中提取数据并将其发送到另一个 html 文件,仅作为每个标题的标题。

There is the JavaScript code,有 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') 
    }) 
});

There is the pull data in NodeJS 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));
});

Some corrections to your code.对您的代码进行一些更正。

$(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'); 
    });
  });
});

In your Each loop, you used i for the Index and item for the Value.在 Each 循环中,您使用i作为索引,使用item作为值。 So i.item should have thrown an error about being undefined.所以i.item应该抛出一个关于未定义的错误。 I switched it to item.title which should give the proper detail.我将其切换为item.title ,它应该提供适当的详细信息。

I also updated the code to use jQuery to create the new HTML Elements.我还更新了代码以使用 jQuery 创建新的 HTML 元素。

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

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