我對Web開發非常陌生。我曾經使用WPF和C#進行桌面開發。現在我正在學習Node.js的將參數傳遞給node.js中的路由
我有一個名爲Party.js模型中,我定義了兩個出口如下:
module.exports.getAllParties = function(callback){
Party.find().lean().exec(function(err, parties){
if (err) return callback(err, null);
callback(null, parties);
});
};
module.exports.getPartyByPartyCode = function(partyCode, callback){
Party.find({partyCode: partyCode}).exec(function(err, party){
if(err) return callback(err, null);
callback(null, party);
});
};
現在,我也有一個名爲Party.js路線,我有二送方法如下:
router.get('/', function(req, res, next){
//retrieve all parties from Party model
Party.getAllParties(function(err, parties) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function(){
res.render('Party', {
title: 'Party',
"parties" : parties
});
},
//JSON response will show all parties in JSON format
json: function(){
res.json(parties);
}
});
}
});
});
router.get('/:partyCode', function(req, res, next){
Party.getPartyByPartyCode(function(err, party) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function(){
res.render('Party', {
title: 'Party',
"party" : party
});
},
//JSON response will show all parties in JSON format
json: function(){
res.json(party);
}
});
}
});
});
現在,當我用ajax:
var inputElem = $('#partyForm :input[name="partyCode"]'),
inputVal = inputElem.val(),
data = { partyCode : inputVal },
eReport = ''; //error report
$.ajax(
{
type: "GET",
url: "/Party",
dataType: "json",
data: data,
beforeSend: function(jqXHR, settings)
{
console.log(settings.url);
},
success: function(party)
{
if (party)
{
console.log(party);
return 'Party ' + party.partyName + ' has already taken party code: ' + party.partyCode + '. Please choose a different PartyCode.';
}
else
{
console.log("party does not exist.");
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
alert('ajax loading error... ... '+url + query);
return false;
}
});
我的問題是:爲什麼高於ajax電話會讓我回到所有的派對?我只是想獲得一個政黨,其patyCode在傳遞給Ajax調用的數據....
您需要將您的party_id添加到您的ajax網址,如下所示 - 「url:」/ Party /「+ party_id,'。那麼你在服務器端的匹配路線應該像'/ Party /:partyCode' –
這個函數如何工作Party.getPartyByPartyCode?我沒有看到它使用任何partyCode作爲輸入。 –
@ManishJangir你能告訴我如何將我的派對代碼傳遞給該函數? – Vishal