2011-03-08 24 views
1

我正在編寫一個函數來發送$ .post顯示請如何正確地將變量插入對象,具體取決於它們是否設置。 這裏是我想要做的:

function SendCommand(Command, QuestionId, Attr) { 
    $.post('/survey/admin/command', 
    { 
    'Command': Command, 
    if (QuestionId) 'QuestionId' : QuestionId, 
    if (Attr) 'Attribute' : Attr 
    } 
    ); 
} 

謝謝!

回答

1

這是實現這種快捷的方式...

$.post('/survey/admin/command', 
    { 
    Command: Command, 
    QuestionId: QuestionId || undefined, 
    Attribute: Attribute || undefined 
    } 
); 

最大的區別這個方法,雖然是有一些是假的一定值(如零或空字符串)。所以這不是所有的方法。

+0

這是最短的 – alega

0

如果有空值的可能性,我會去用:

$.post('/survey/admin/command', 
    { 
    'Command': Command, 
    'QuestionId' : QuestionId ? QuestionId : undefined, 
    'Attribute' : Attribute ? Attribute : undefined, 
    } 
); 

否則,我認爲jQuery將忽略未定義PARAMS。

3

你總是可以創建你的數據.post的$調用之前

var data = { 
'Command': Command 
}; 

if (QuestionId) { 
    data.QuestionId = QuestionId; 
} 
if (Attribute) { 
    data.Attribute = Attribute; 
} 

$.post("your/url", data); 
0

試試這個(未經測試)

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 ); 
}