如何使用一个变量作为对象初始化器里面的关键 [英] How to use a variable as a key inside object initialiser

查看:125
本文介绍了如何使用一个变量作为对象初始化器里面的关键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的工作中的应用,服务器页面用来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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆