我对此完全是初学者。我在互联网上无休止地搜索,但我就是无法找出问题所在。可能我犯了一些基本的概念错误,所以任何帮助将不胜感激。
我想使用 javascript
进行简单的表单输入或jquery
和一个ajax
要求。这是相关代码。
//JavaScript:
function sendMails(){
console.log("This is executing");
var data={
first_name: $("#first_name").val(),
email: $("#email").val(),
toArtists: $("#toArtists").val(),
comments: $("#comments").val(),
bcc_Emails: $("#bcc_Emails").val()
};
$.ajax({
url: "/sendMailsToArtists",
type: "POST",
cache: false,
async: true,
data: data,
//data: $("commentform").serialize(),
success: function(data){
alert('Success!')
console.log("This is executingggggg");
}
,
error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err)
}
});
//return false;
}
<form class="form-horizontal" name="commentform" id="commentform">
//Some fields
<button type="submit" value="Submit" class="btn btn-custom pull-right" id="send_btn" onclick="sendMails()">Send</button>
</form>
URL 包含在名为 app.js
的文件中我为服务器运行的。
线路"This is executing"
打印在控制台上。然后弹出警报并显示消息 "text status error, err"
。然后页面导航到类似 "http://localhost:3000/contactArtists?first_name=ohohoo&email=mallika13055%4…"
的 URL。
如果这是非常基本的东西,请原谅。
编辑:
好的,所以我改为 <button type = "button">
.
这是服务器端代码:
app.post('/sendMailsToArtists', function (req, res){
console.log(req.body);
});
数据被打印在终端上。这是否意味着没有错误?那为什么ajax请求的成功分支没有被执行呢?
编辑2:
已经解决了。 res.send() 完成这项工作。
最佳答案
您正在使用提交按钮,该按钮会提交表单,因此使用type='button'
它将起作用
<button type="button" value="Submit" class="btn btn-custom pull-right" id="send_btn" onclick="sendMails()">Send</button>
关于javascript - JavaScript 和 Express 中的 AJAX 请求出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30435742/