2

In the application I am working, the server pages are used to recieving an input's name as the key for it's value. Is is possible to do this with ajax? In this example, thisName is treated as a literal string.

$('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 )
        }
    });
});
4

2 回答 2

1

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

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

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

然后fields在您的$.ajax通话中使用data: fields

于 2012-05-17T06:48:34.780 回答
0

也许不那么优雅,但是:

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

于 2012-05-17T17:32:34.270 回答