简体   繁体   中英

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);
  });
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM