2011-03-08 11 views
1

$ .postを送信する関数を書いています。設定されているかどうかによってオブジェクトに変数を正しく挿入する方法を教えてください。ここ は私がやろうとしているものです:

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

ありがとう!

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

は、そうでなければ、私はjQueryのは、未定義のparamsを無視すると思う:NULL値の可能性がある場合に

答えて

1

...

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

この方法の最大の没落は、偽である(例えば、ゼロまたは空の文字列など)特定の値があるということです。だから、これはすべての方法をキャッチすることではありません。

+0

(未テスト)これを試してみてください前に、あなたは常にあなたのデータを作成することができます – alega

0

、私は行くだろう。しかしこれは、これを実装するための簡単な方法です

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 ); 
} 
関連する問題