开发者

How would I modify my jQuery ajax response to do the same thing with JSON that it currently does by returning JavaScript?

$('.showprayer').click( function(event) 
{
  $.post('/show_prayer', { 'name' : $(this).text() }, function(data) 
  {
      eval(data);
  });
});
开发者_StackOverflow

The jQuery function above returns the following string as the ajax response coming back from the server:

'#prayer_date'.html("03/19/1968");

Someone seeing this code earlier responded that "returning javascript instead of JSON is a terrible way of using Ajax".

My problem is, I thought this was the only way of doing it.

So if someone could enlighten me . . . if I wanted to do the same thing by returning JSON, what would that look like and would it involve significantly more code than my current ajax response which very succinctly changes the value of the prayer_date element to its new date value?


Just have the server return the date as a JSON object and reference the property in the client. Don't forget to let the AJAX function know what type of data is expected since you won't be returning the default (html).

$('.showprayer').click( function(event) 
{
  $.post('/show_prayer', { 'name' : $(this).text() }, function(data) 
  {
      $('#prayer_date').html(data.Date);
  },'json');
});

Server returns:

"{ 'Date' : '03/19/1968' }"


You should return just the json object like { "date": "03/19/1968" } and then rather than doing an eval, do $("#prayer_date").text(data.date); (or html as you show in your example. So, the bottom line is that the code being called ultimately is the same, but it's designed a bit better, and you aren't using eval.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜