我正在尝试使用Ajax调用提交表单数据。相关的表单代码就像。
<form target="_blank" id="addCaseForm" class="form-horizontal col-md-12" action="" method="POST">
<div class="form-group">
<label class="col-md-3 control-label">Patient Name</label>
<div class="col-md-9">
<input type="text" class="form-control" id="patientName" name="patientName" placeholder="" required>
</div>
</div>
.. .. .. .. ..
<button type="submit" class="btn btn-primary btn-xs">Save</button>
</form>
点击提交按钮,下面的事件被调用,我正在对node.js服务器进行正常的Ajax调用以提交表单数据。首先,我已经将表单数据序列化并将其作为附加参数传递给request.sent。
但是如何在服务器端获取此数据。我尝试了多种方法来获取像 req.body这样的数据。 patientName , req.params('patientName')但没有任何效果。我错过了什么。
$("#addCaseForm").submit(function(event) {
var postData = $(this).serialize();
// "patientName=rtgh&patientFatherName=5tryh&patientDob=10%2F08%2F2014&patientBloodGroup=o&patientAge=25&patientSex=M&patientNationality=Indian&patientPhone=76&Specilizationtag=3&patientDesc=uyhjn"
event.preventDefault();
var request;
try {
request = new XMLHttpRequest();
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null) {
console.log("Error::Unable to create request object at add new case");
return false;
}
request.open('POST', '/addNewCase', true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
console.log("Form successfully submitted");
}
}
};
request.send(postData);
});
如何在节点服务器端获取表单数据?
我正在使用express,节点代码在
之下exports.addNewCase = function(req,res){
var Specilizationtag = [],
attachemntTag = [];
Specilizationtag = req.params('Specilizationtag').split(',').map(function(eachTag){
return parseInt(eachTag);
});
var patient = new Patient({
name: req.params('patientName'),
fatherName: req.params('patientFatherName'),
dob:new Date(req.params('patientDob')),
bloadGroup : req.params('patientBloodGroup'),
age:req.params('patientAge'),
sex: req.params('patientSex'),
nationality:req.params('patientNationality'),
phone: req.params('patientPhone'),
description: req.params('patientDesc'),
specialization:Specilizationtag,
attachmentId:attachemntTag});
patient.save(function(err){
if(err) {console.log("Error Occured"+err);};
});
res.end();
};
答案 0 :(得分:0)
在请求对象中添加内容类型解决了问题。
调用setRequestHeader()并将其内容类型设置为&#34; application / x-www-form-urlencoded&#34;。这是通过Ajax发出的任何POST请求所必需的。
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");