I have two data objects stored on开发者_StackOverflow中文版 different nodes in the dom
ie
$('node1').data('id','1');
$('node2').data('id','1');
How do I combine these in order to attatch them to the data attribute in the ajax object
$.ajax({
url: 'http://localhost:8080/test.html',
timeout: 3000,
cache: false,
data: // combined node1 and node2 here!,
success: function(data){
}
});
Thanks in advance
You have a couple of options. Here's how I'd do it:
data: {node1: $('node1').data('id'), node2: $('node2').data('id')},
...because jQuery will accept an object and generate the necessary URI-encoded representation for you (see the data
parameter in the ajax
docs).
But you can also do it using encodeURIComponent
and string concatenation:
data: "node1=" + encodeURIComponent($('node1').data('id')) + "&" +
"node2=" + encodeURIComponent($('node2').data('id')),
You can see why I prefer the first syntax. :-)
Either way, your script will see node1
and node2
parameters in the HTTP data (in your case, the query string, since your ajax
call is using the default GET
method).
If you wanted a single parameter with a combined value, just choose a separator (or don't use one) and combine the two values. Here's an example using an _
for the separator:
data: {paramName: $('node1').data('id') + "_" + $('node2').data('id')},
// -or-
data: "paramName=" + encodeURIComponent(
$('node1').data('id') + "_" +
$('node2').data('id')
),
精彩评论