如何使用一个变量作为对象初始化器里面的关键 [英] How to use a variable as a key inside object initialiser
问题描述
在我的工作中的应用,服务器页面用来recieving输入的名称作为它的价值的关键。是可以使用Ajax做到这一点? 在这个例子中,thisName被视为文字串
$('表')。每个(函数(){
$(本).delegate(输入,事件的内容,函数(){
VAR thisValue = $(本).VAL();
VAR thisName = $(本).attr('名');
$阿贾克斯({
超时:3000,
//缓存:假的,
数据: {
p_session_id:$([名称='p_session_id'])VAL()
p_username:$([名称='p_username'])VAL()。
thisName:thisValue
// ^^
},
成功:功能(数据){
警报(数据)
}
});
});
不幸的是,一个对象初始化器上的左侧部分内:
不被视为一个可变的,但作为一个字符串,所以 the_key
被认为是一样的the_key
。
这是最直接的方法,我能想到的一个动态的名字添加属性:
VAR领域= {
p_session_id:$([名称='p_session_id'])VAL()
p_username:$([名称='p_username'])VAL()。
}
域[thisName] = thisValue;
然后使用你的 $ AJAX
字段
电话为数据:场
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 )
}
});
});
Unfortunately, inside an object initialiser the part on the left side of the :
is not treated as a variable but as a string, so the_key
is regarded the same as "the_key"
.
This is the most straightforward way I can think of to add properties with a dynamic name:
var fields = {
p_session_id: $("[name='p_session_id']").val(),
p_username: $("[name='p_username']").val()
}
fields[thisName] = thisValue;
Then use fields
in your $.ajax
call as data: fields
这篇关于如何使用一个变量作为对象初始化器里面的关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!