一个简单的 AJAX 实现
你应该有基本的快速生成器模板
在 app.js 中,添加(你可以在 var app = express.app()
之后的任何地方添加它):
app.post(function(req, res, next){
next();
});
现在在 index.js 文件(或其各自的匹配项)中,添加:
router.get('/ajax', function(req, res){
res.render('ajax', {title: 'An Ajax Example', quote: "AJAX is great!"});
});
router.post('/ajax', function(req, res){
res.render('ajax', {title: 'An Ajax Example', quote: req.body.quote});
});
在/views
目录中创建 ajax.jade
/ ajax.pug
或 ajax.ejs
文件,添加:
对于 Jade / PugJS:
extends layout
script(src="http://code.jquery.com/jquery-3.1.0.min.js")
script(src="/magic.js")
h1 Quote: !{quote}
form(method="post" id="changeQuote")
input(type='text', placeholder='Set quote of the day', name='quote')
input(type="submit", value="Save")
对于 EJS:
<script src="http://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="/magic.js"></script>
<h1>Quote: <%=quote%> </h1>
<form method="post" id="changeQuote">
<input type="text" placeholder="Set quote of the day" name="quote"/>
<input type="submit" value="Save">
</form>
现在,在/public
中创建一个名为 magic.js
的文件
$(document).ready(function(){
$("form#changeQuote").on('submit', function(e){
e.preventDefault();
var data = $('input[name=quote]').val();
$.ajax({
type: 'post',
url: '/ajax',
data: data,
dataType: 'text'
})
.done(function(data){
$('h1').html(data.quote);
});
});
});
你有它! 当你单击保存时,引号将会更改!