Javascript jquery如何组合data()对象
我有两个数据对象存储在dom中的不同节点上 即 如何组合这些属性,以便将它们附加到ajax对象中的数据属性Javascript jquery如何组合data()对象,javascript,jquery,Javascript,Jquery,我有两个数据对象存储在dom中的不同节点上 即 如何组合这些属性,以便将它们附加到ajax对象中的数据属性 $.ajax({ url: 'http://localhost:8080/test.html', timeout: 3000, cache: false, data: // combined node1 and node2 here!, success: function(data){ } }); 提前感谢您有两种选择。我是这样做的: data: {node1:
$.ajax({
url: 'http://localhost:8080/test.html',
timeout: 3000,
cache: false,
data: // combined node1 and node2 here!,
success: function(data){
}
});
提前感谢您有两种选择。我是这样做的:
data: {node1: $('node1').data('id'), node2: $('node2').data('id')},
…因为jQuery将接受一个对象,并为您生成必要的URI编码表示(请参阅中的数据
参数)
但您也可以使用和字符串连接:
data: "node1=" + encodeURIComponent($('node1').data('id')) + "&" +
"node2=" + encodeURIComponent($('node2').data('id')),
您可以了解我为什么喜欢第一种语法。:-)
无论哪种方式,脚本都会在HTTP数据中看到node1
和node2
参数(在您的例子中,查询字符串,因为您的ajax
调用使用默认的GET
方法)
如果您想要一个具有组合值的单个参数,只需选择一个分隔符(或不使用分隔符)并组合这两个值。下面是一个使用\uu
作为分隔符的示例:
data: {paramName: $('node1').data('id') + "_" + $('node2').data('id')},
// -or-
data: "paramName=" + encodeURIComponent(
$('node1').data('id') + "_" +
$('node2').data('id')
),
data: {paramName: $('node1').data('id') + "_" + $('node2').data('id')},
// -or-
data: "paramName=" + encodeURIComponent(
$('node1').data('id') + "_" +
$('node2').data('id')
),