使用 Jquery ajax json 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19367905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Jquery ajax json response?
提问by Ziplo
:have an ajax request looking like this :
:有一个看起来像这样的ajax请求:
$.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 :
因此,如果该功能成功,则会删除“禁用”类。但是,我的函数返回以下 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"
我想得到这个值,以便我以后可以使用它“将它添加到数据元素,即我想添加到点击的元素 data-row="fze684fz6f4ez68f4ze"
How can I manage this ? I can't figure out by myself, I'm discovering AJAX.
我该如何管理?我自己无法弄清楚,我正在发现 AJAX。
Thanks a lot for your help !
非常感谢你的帮助 !
回答by Dvir
It's recommend to set dataType
if you excpect to get json .
Any way pay attention to the context. It might be a problem with this
.
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);
}
});
回答by SLaks
As the documentation clearly states, jQuery passes the server's response as the first parameter to the success
callback:
正如文档明确指出的那样,jQuery 将服务器的响应作为第一个参数传递给success
回调:
success : function (response) {
console.log(response);
}
回答by Adil
You can use jQuery.data( element, key )to assign row from returned response to element
您可以使用jQuery.data( element, key )将返回的响应中的行分配给元素
$('selector').data('row', reseponse.row);
You can use id selector if you know the id of element
如果您知道元素的 id,则可以使用 id 选择器
$('#elementId').data('row', response.row);
You can read more about selectors here.
您可以在此处阅读有关选择器的更多信息。
Your code would be
你的代码是
$.ajax({
url: "/users/action/",
type: "POST",
data: myData,
context: this,
error: function () {},
success : function () {
$(this).removeClass('disabled');
$('#elementId').data('row', response.row);
}
});