2011-03-08 6 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

당신은 항상

var data = { 
'Command': Command 
}; 

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

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

이 (안된)보십시오 $ .post 호출하기 전에 데이터를

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 ); 
} 
관련 문제