开发者

JQuery super basics. Why can't I access data.html, when I see data variable?

开发者 https://www.devze.com 2023-03-19 10:59 出处:网络
I\'m working with JQuery-ujs + Rails. and I\'m 90% to the problem\'s solution but stumped: I see success on screen

I'm working with JQuery-ujs + Rails. and I'm 90% to the problem's solution but stumped:

  1. I see success on screen
  2. I see data
  3. I can't see data.html => why?? How can I access this? I see it in the hash below in my logs.

Here is what I am dealing with:

$(function(){
  $('#add-mod-form').bind('ajax:success', function(evt, data, status, xhr){
      alert("Success!");
      console.log(data.success);
      console.log(data.html);
      console.log(xhr.responseText);
      console.log(evt);
      console.log(data);
      console.log(status);
      console.log(xhr);

//works!
      $('#page').append(xhr.responseText);

//does not work!
      $('#page').append(data.html);

  });
});

Here is my logs:

undefined
undefined
{"success":true,"html":"<div class=\"extrafield\" id=\"extrafield_73\">\n<div class='trash_can'>Nala <a href=\"#\" data-confirm=\"Are you sure you want to delete Nala?\" data-href=\"/delete_extra_field/73\"><img alt=\"Trash\" src=\"http://\" /></a></div>\n</div>\n"}
Object { type="ajax:success", timeStamp=1310160257936, more...开发者_StackOverflow中文版}
{"success":true,"html":"<div class=\"extrafield\" id=\"extrafield_73\">\n<div class='trash_can'>Nala <a href=\"#\" data-confirm=\"Are you sure you want to delete Nala?\" data-href=\"/delete_extra_field/73\"><img alt=\"Trash\" src=\"http://\" /></a></div>\n</div>\n"}
success
Object { readyState=4, responseText="{"success":true,"html":"<div class=\"extrafield\" id=\"extrafield_73\">\n<div class='trash_can'>Nala <a href=\"#\" data-confirm=\"Are you sure you want to delete Nala?\" data-href=\"/delete_extra_field/73\"><img alt=\"Trash\" src=\"http://\" /></a></div>\n</div>\n"}", more...}


It's because your data is a json string and not an object. You should do:

  $('#add-mod-form').bind('ajax:success', function(evt, data, status, xhr){
      data = $.parseJSON(data); //This converts 'data' from json string to object
      alert("Success!");      
      //The rest of your code
  });

Note that $.parseJSON decodes from json string to object.

Hope this helps. Cheers


also html is a method. Use data.html() instead.

0

精彩评论

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

关注公众号