【问题标题】:How to use a variable as a key inside object initialiser如何在对象初始化程序中使用变量作为键
【发布时间】:2012-05-17 06:39:21
【问题描述】:

在我正在工作的应用程序中,服务器页面用于接收输入的名称作为其值的键。可以用ajax做到这一点吗? 在此示例中,thisName 被视为文字字符串。

$('table').each(function(){ 
    $(this).delegate("input", "focusout", function(){
        var thisValue = $(this).val();
        var thisName = $(this).attr('name');
        $.ajax({
            timeout: 3000,
            //cache: false,
            data: {
                p_session_id: $("[name='p_session_id']").val(),
                p_username: $("[name='p_username']").val(), 
                thisName: thisValue
//              ^^
            },
            success: function(data){
            alert( data )
        }
    });
});

【问题讨论】:

  • 尝试数据:{p_session_id: $("[name='p_session_id']").val(), p_username: $("[name='p_username']").val(), (thisName): thisValue},即(thisName): thisValue

标签: javascript jquery ajax


【解决方案1】:

不幸的是,在对象初始化器中,: 左侧的部分不被视为变量而是字符串,因此the_key 被视为与"the_key" 相同。

这是我能想到的最直接的方法来添加具有动态名称的属性:

var fields = {
    p_session_id: $("[name='p_session_id']").val(),
    p_username: $("[name='p_username']").val()
}
fields[thisName] = thisValue;

然后在您的$.ajax 调用中使用fields 作为data: fields

【讨论】:

    【解决方案2】:

    也许没有那么优雅,但是:

    function makeObj (a) {
      if (!(a instanceof Array))
        throw ('Attempt to build object from ' + (typeof a));
      if (a.length % 2)  
        throw ('Attempt to build object from an array length ' + a.length);
    
      for (var o = {}, i = a.length - 1; i > 0; i -= 2) {
        console.log (a[i-1], a[i]); 
        o[a[i - 1]] = a[i];
      }  
      return o;
    }
    
    var thisName = 'Hans PUFAL';
    var thisValue = 'Paleoinformaticien';
    var session_id = '123edrft456fg';
    
    var o = makeObj (['p_session_id', session_id,
                  'p_username', 'HBP',
                  thisName, thisValue]);
    

    可在此处获取:http://jsfiddle.net/jstoolsmith/bZtpQ

    【讨论】:

      猜你喜欢
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 2019-08-28
      • 1970-01-01
      相关资源
      最近更新 更多