2

I have an array of strings that I would like to append to a url in an ajax request. There are some additional string that i need to add to the Url along with the array string.

html

<ul>
  <li data-url="string1"></li>
  <li data-url="string2"></li>
  <li data-url="string3"></li>
  <li data-url="string4"></li>
  <li data-url="string5"></li>
</ul>

So far in my javascript i have something like this:

javascript

//create empty array
var data = [];

$('ul li').each(function(){
  data.push(this.getAttribute('data-url'));
})
// now in data I have : ['string1','string2', 'string3' ..]

// here is where im lost
// how to concat those array items into the url with the '&'  symbol
var url = 'www.foo.com/bar=' data + '&'

//Make an ajax request
$ajax({
  url: url,
  method: 'POST',
 })

overall I would like the url to look something like this:

www.foo.com/bar=string1&bar=string2&bar=string3
1
  • 1
    Wouldn't that overwrite previous bar values? Don't you mean bar[]? Commented Oct 14, 2015 at 16:13

2 Answers 2

1

You can do something simple like this,

// using map iterate and get data value
var data = $('ul li').map(function() {
  return 'bar=' + $(this).data('url');
  // using data() you can get data attribute value
}).get().join('&');
// using get() you can get retuned value as an array
// joing the array using join()

var url = 'www.foo.com/' + data;

console.log(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li data-url="string1"></li>
  <li data-url="string2"></li>
  <li data-url="string3"></li>
  <li data-url="string4"></li>
  <li data-url="string5"></li>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

0

Why don't you try an alternate like following

var data = "";

$('ul li').each(function(){
  data += "bar="+this.getAttribute('data-url') + "&";
})

data = data.substring(0, data.length-1);

var url = 'www.foo.com/' + data;

//Make an ajax request
$ajax({
  url: url,
  method: 'POST',
 })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.