简体   繁体   English

如何使用 Ajax 从服务器端(nodejs)发送 JSON 到客户端?

[英]How to send JSON from server-side (nodejs) to client-side with Ajax?

I've created a Node.js/express server to GET call API.我创建了一个 Node.js/express 服务器来获取调用 API。 The API returns a json data. API 返回 json 数据。 How do I send the JSON I've received to my local javascript (client-server)?如何将收到的 JSON 发送到本地 javascript(客户端-服务器)? I'd like to grab this JSON, send to my local client (with an ajax call if this is the option), loop through it and append it to my DOM!我想抓住这个 JSON,发送到我的本地客户端(如果可以选择,则使用 ajax 调用),循环遍历它,然后将 Z9516DFB15F51C7EE19A4D46B8DOMC0DBE1DZ 发送给我!

app.js应用程序.js

var express = require('express');
var router = express.Router();
var request = require("request");

let name, value, bodyData;

var options = { method: 'GET',
  url: 'https://api.example.com/data1',
  qs: 
   { 
     valueType: 'MAXIMUM'
   },
  headers: 
   { 
     authorization: 'ABC123456',
     accept: 'application/json; charset=utf-8' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  bodyData = body;

});


router.get('/', function(req, res, next) {
  res.render('home', {data: bodyData});
});

module.exports = router;

app.ejs应用程序.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Items</title>
</head>
<body>
  <div id="itemsList">
    <h2>List of available items:  </h2>
  </div>
</body>
</html>

scripts.js脚本.js

$(document).ready(function(){
   $.ajax({
       type: "GET",
       url: "http://localhost:3000/",
       contentType: "application/json"
     }).done(function(data){
          for(var i =1; i<= 10; i++){
          $('#itemsList').append('<div id="r'+ i +'"></div>')
          }
     })
 });
var express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));


app.get('/', (request, response)=>{
  response.json({
    message: 'Hello world!',
    arrayText: ['message1', 'message2']
  }):
});

If your data is an array then you should write loop in this way:如果您的data是一个数组,那么您应该以这种方式编写循环:

$(document).ready(function(){
   $.ajax({
       type: "GET",
       url: "http://localhost:3000/",
       contentType: "application/json"
     }).done(function(data){
          for(var i =1; i<data.length; i++){
          $('#itemsList').append('<div id="r'+ data[i] +'">'+data[i]+'</div>')
          }
     })
 });

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

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