3

:have an ajax request looking like this :

$.ajax({
          url: "/users/action/",
          type: "POST",
          data: myData,
          context: this,
          error: function () {},
          success : function () {
        $(this).removeClass('disabled');
          }
        });

So if the function is successfull, the class "disabled" is removed. However, my function returns the following json :

{"row":"fze684fz6f4ez68f4ze"}

I want to get this value so I can use it later "add it to a data element, i.e I want to add to the clicked element data-row="fze684fz6f4ez68f4ze"

How can I manage this ? I can't figure out by myself, I'm discovering AJAX.

Thanks a lot for your help !

4

3 回答 3

8

dataType如果您期望获取 json ,建议设置。无论如何都要注意上下文。这可能是一个问题this

$.ajax({
    url: "/users/action/",
    type: "POST",
    data: myData,
    context: this,
    error: function () {},
    dataType: 'json',
    success : function (response) {
        $(this).removeClass('disabled');
        $(this).data("row",response.row);
    }
});
于 2013-10-14T19:43:08.223 回答
3

正如文档明确指出的那样,jQuery 将服务器的响应作为第一个参数传递给success回调:

      success : function (response) {
         console.log(response);
      }
于 2013-10-14T19:38:19.313 回答
2

您可以使用jQuery.data( element, key )将返回响应中的行分配给元素

$('selector').data('row', reseponse.row);

如果您知道元素的 id,则可以使用 id 选择器

$('#elementId').data('row', response.row);

您可以在此处阅读有关选择器的更多信息。

你的代码是

$.ajax({
      url: "/users/action/",
      type: "POST",
      data: myData,
      context: this,
      error: function () {},
      success : function () {
           $(this).removeClass('disabled');
           $('#elementId').data('row', response.row);
     }
});
于 2013-10-14T19:39:59.003 回答