1

I have 3 spans on my page that contain numbers. On click of a button I would like to retrieve an ajax response, and if the response is valid (it should be an array of 3 elements) I would like to update the numbers in these spans. Could you please recommend a solution via jQuery?

Thank You.

2 Answers 2

2
$.getJSON(url, function(resp)
{
  var list = resp.list;
  if(!list)
  {
    throw new Exception("list is not set");
  }
  for(var i = 0; i < list.length; i++)
  {
    $('#span' + (i + 1)).text(list[i]);
  }
});

if the spans have ids span1, span2, and span3. See $.getJSON for more information. Note that you can add error handling by using $.ajax instead.

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

2 Comments

Thank you for your help. Quick question: what should a resp string look like?
By the time it gets to your callback, it's no longer a string. However, before jQuery parses it, it will look like {"list": ["foo", "bar", "baz"]}
0

You can just implement this by usig jQuery.getJson(url,callback(data,textStatus)) .

for example :

$.getJSON(url, function(data,textStatus){ var spanValues = data.list; $('#span_Id').text(spanValues [i]); ...

});

1 Comment

It's trivial question ,and the answer from Mattew Flaschen is same but better one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.