您好,我已经学习了AJAX和POST和GET方法的基础知识,但是我一定做错了,因为我的警报从原始HTML文件返回了文本,而不是从服务器返回了数据。我正在尝试从文本字段中获取参数,并将其发送到服务器。然后,服务器将会话值发送回客户端。这只是我的代码需要做什么的简化视图。下面是我的代码:
Index.html:
`
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<form method="post">
<input type="text" name="args" id="args">
<button id="submitButton" >Submit</button>
</form>
<script>
$('#submitButton').on("click", (function(event){
event.preventDefault();
var args = $('#args').val();
$.ajax({
url: "/",
type:"POST",
data:{args:args},
success: function(data){alert(data)},
error: function(){alert("Error occurred posting");}
});
}));`
</body>
Index.js:
var express = require('express');
const spawn = require('cross-spawn').spawn;
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
//DEFINITIONS
var app = express();
app.use(cookieParser());
app.use(bodyParser.json()); //support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true})); //support encoded bodies
//Sessions.
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
}));
//ROUTES
app.get('/', function(req,res){
res.sendFile('../public/index.html', {root : __dirname});
});
app.post('/', function(req,res){
var session = "hello";
//Adds session ID to args
var args = req.body.args + " -o " + session;
//Calls method with these arguments
runFunction(args);
//Sends session variable back to client
res.send(session);
});
exports.app = functions.https.onRequest(app);
控制台中没有错误。我在Index.js中添加了console.log()语句,但是没有一个被打印出来,这意味着该发布/获取从未实现。我添加了警报,以查看返回了什么,并且它不断返回Index.html的文本。我可能做错了什么?谢谢。