利用next(),在ajax请求结束后,传递信息给next(作为参数),使用yield来接收参数
node.js文件
/**
* Created by 10853 on 2020/2/1.
*/
//引入模块
var express=require('express');
//创建服务器
var app=express();
app.set('View engine','ejs');
app.set('views','./');
//开启服务器并监听端口
app.listen(3000,function(){
console.log('this express server is running at http://127.0.0.1:3000 ');
})
app.get('/', function (req, res, next) {
res.render('index.ejs', {title: 'Express'});
});
app.get('/news', function (req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
var id = req.query.id;
console.log('/news id='+id);
var news = {
id: id,
title: 'news title1...',
content: 'news content1...',
commentsUrl: '/comments?newsId='+id
};
res.json(news);
});
//根据前一个路由返回的Url路径,获得另一个路由地址,和查询新闻的id
app.get('/comments', function (req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
console.log('/comments newsId=' + req.query.newsId);
var newsId = req.query.newsId;
var comments = [
{
id: 1,
content: 'comment content1111...',
newsId : newsId
},
{
id: 2,
content: 'comment content2222...',
newsId : newsId
}];
res.json(comments);
});
module.exports=app;
html文件:
<html ng-app='app' ng-controller='main' >
<head>
<meta charset="utf-8">
<meta name='viewport' content='width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0'>
<script src='jq/jquery-3.4.1.js'></script>
<style>
</style>
</head>
<body >
<script>
function getNews(url)
{
$.get(url,function(data){
let url=data.commentsUrl
//在上一个请求成功时,调用next方法,给上一个yield作为返回值
ite.next(url);
console.log(data);
})
}
function *sendXml()
{
//接收第二次next中的参数
let url=yield getNews('http://localhost:3000/news?id=2');
yield getNews('http://localhost:3000'+url)
}
//获得遍历器对象
let ite=sendXml();
ite.next();
</script>
</body>
</html>