[英]AJAX Request to read JSON object from node.js/express server
我設置了一些服務器端代碼,以向外部網站發出請求,並返回一個JSON對象,然后將該對象傳遞到我的node.js / express應用程序的客戶端。 然后,我打算在客戶端的JSON上執行一些其他處理。
在我的index.js文件中,定義了以下代碼以呈現我的視圖並對外部網站進行RESTful調用:
var express = require('express');
var router = express.Router();
var request = require('request');
// Urls for external server REST API function calls
var url = 'https://someserver.com/appserver/portal/api/1.0/results/recent';
/* GET list of recent reports */
router.get('/testapi', function(req, res, next) {
res.render('testapi', { title: 'List Recent Reports' });
});
/* TEST: function to GET report list */
router.get('/recentreports', function(req, res){
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
res.send(body); // Send the response to the client
} else {
console.log(error);
}
})
});
module.exports = router;
在我的Jade視圖中,我設置了一個按鈕來調用/ recentreports函數並發出一個請求(可能是AJAX請求?)以從服務器接收JSON對象。
我的問題是:如何將服務器的響應讀入客戶端應用程序,以便處理JSON?
我的玉觀如下:
extends layout
head
block content
h1= title
p Welcome to #{title}
script.
// not sure what goes here
$(function()){
$('#getRecentReports').on('', function() {
$.get('recentreports', function(body) {
$('#jsonbody').html(body)
})
})
}
button(
onclick = "getRecentReports()"
)
編輯:玩了之后更新了.jade代碼
我的建議:
script.
$(function() {
$('#getRecentReports').on('click', function() {
$.get('recentreports', function(body) {
$('#jsonbody').html(body)
});
});
});
button(
id = "getRecentReports"
)
呈現此:
<script>
$(function() {
$('#getRecentReports').on('click', function() {
$.get('recentreports', function(body) {
$('#jsonbody').html(body)
});
});
});
</script>
<button id="getRecentReports"></button>
或者:
script.
function getRecentReports() {
$.get('recentreports', function(body) {
$('#jsonbody').html(body)
});
}
button(
onclick = "getRecentReports()"
)
呈現此:
<script>
function getRecentReports() {
$.get('recentreports', function(body) {
$('#jsonbody').html(body)
});
}
</script>
<button onclick="getRecentReports()"></button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.