我目前正在尝试建立简单的在线论坛,人们可以发表评论;但是,我不确定我写的是正确的方法。通过选择type =“POST”提交表单后会自动调用Ajax吗?
我也不确定我是否在路线文件中写了正确的程序。
这是我的代码。
<!DOCTYPE>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// $(function(){
// $("#target").submit(function(event){
// event.preventDefault();
// $.post("/users", function(data){
// $( "#result" ).html( JSON.stringify(data) );
// });
// });
// });
//Not sure which way I should use ↑↓
$.ajax({
type: "GET",
url: 'http://localhost3000/users',
data: data,
dataType: 'json'
})
.done(function(data){
console.log("GET Succeeded");
$('#result').html(JSON.stringify); //What should I put after JSON.stringify?
});
$(function(){
$("#target").submit(function(event){
$.ajax({
type: "POST",
url: 'http://localhost3000/users',
data: data,
dataType: 'json'
})
.done(function(data){
console.log("POST Succeeded");
$('#result').html(JSON.stringify); //What should I put after JSON.stringify?
});
});
});
</script>
</head>
<body>
<div id="result"></div>
<form action="/users" method="post" id="target">
Username:<input type="text" name="username">
<input type="submit" value="Post">
</form>
</body>
</html>
这是我的路线文件
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Users = require('../models/users');
var userRouter = express.Router();
userRouter.use(bodyParser.json());
userRouter.route('/')
.get('/users', function (req, res, next) {
Users.find({}).then(function(user){
res.json(user)
}).catch(next);
})
.post(function(req, res, next){
// res.send("Confirmed");
Users.create(req.body).then(function(user){
res.send(user);
}).catch(next);
res.json(newUser);
});
module.exports = userRouter;
这是我的app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var url = 'my database';
mongoose.connect(url);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("Connected correctly to server");
});
var routes = require('./router/index');
var userRouter = require('./router/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', userRouter);
//Error handler for user
app.use(function(err, req, res, next){
res.status(422).send({error: err.message});
});
//catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
if (app.get('env') === 'development'){
app.use(function(err, req, res, next){
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
});
app.use(function(err, req, res, next){
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
谢谢:)
答案 0 :(得分:0)
我建议postman
chrome插件,它是一个安静的api客户端,你首先通过它调用api,然后如果api执行完美,你可以编写ajax post else。
答案 1 :(得分:0)
在提交表单时,不会自动调用您的ajax帖子。但是,这就是说,浏览器确实向表单标记中的指定端点发送post
。
如果您需要在发布帖子时自动显示评论,那么您可以在脚本中使用注释的代码块。
另一种方法是做以下事情......
$(function(){
$("#target").submit(function(event){
// add code here to append the form data to the DOM
// dont call event.preventDefault()
// doing so will take advantage of the browser's
// post functionality while giving you a chance
// to handle the form data locally prior to the post
});
});