Insert variables into $.post within a function
i'm writing a function to send $.post show please how to correctly insert variables into object depending if they are set. here is what i'm trying to do:
function SendCommand(Command, QuestionId, Attr) {
$.post('/survey/admin/command',
{
'Command': Command,
if (QuestionId) 'QuestionId' : QuestionId,
开发者_开发问答 if (Attr) 'Attribute' : Attr
}
);
}
Thanks!
You can always create your data before the $.post call
var data = {
'Command': Command
};
if (QuestionId) {
data.QuestionId = QuestionId;
}
if (Attribute) {
data.Attribute = Attribute;
}
$.post("your/url", data);
This is quick way to implement this...
$.post('/survey/admin/command',
{
Command: Command,
QuestionId: QuestionId || undefined,
Attribute: Attribute || undefined
}
);
The biggest downfall to this method, though is that there are certain values (such as zero or an empty string) that are false. So this is not a catch all method.
If there's the possibility of null values, I'd go with:
$.post('/survey/admin/command',
{
'Command': Command,
'QuestionId' : QuestionId ? QuestionId : undefined,
'Attribute' : Attribute ? Attribute : undefined,
}
);
Otherwise, I think jQuery will ignore undefined params.
Try this(untested)
function SendCommand(Command, QuestionId, Attr) {
var data = {};
data['Command'] = Command;
if (QuestionId) data['QuestionId'] = QuestionId;
if (Attr) data['Attribute'] = Attr;
$.post('/survey/admin/command',data );
}
精彩评论