how to assign variable value as variable name in a hash?

后端 未结 3 2166
后悔当初
后悔当初 2020-12-16 11:32

I need to define a hash for posting some ajax data using jQuery. The hash will look something like:

var setname = \'set_1\';
elements = { set_1: {\'beer\',\'         


        
3条回答
  •  生来不讨喜
    2020-12-16 12:12

    You have to understand that there's really no such thing as "JSON notation" in Javascript - it's native Javascript notation that we're talking about. What jQuery wants is a Javascript value for the POST data, not necessarily a Javascript object constant.

    Thus, your code will prepare your POST data like this:

    var elements = {};
    elements[setName] = { /* something */ };
    elements[somethingElse] = { /* something else */ };
    

    and so on. When you're ready to do the POST, you'd just use "elements":

    $.post(url, elements, function() { /* callback code */ });
    

提交回复
热议问题