gpt4 book ai didi

jquery - $.ajax() 访问 did() 中发送的值

转载 作者:行者123 更新时间:2023-12-01 00:23:32 25 4
gpt4 key购买 nike

想象一下:

$('#blah').on('click', function(){
var cat_id = $(this).attr('id');
$.ajax({
// stuff...
data: {cat_id: cat_id}, // <--------------------
// stuff...
}).done(function(){
alert(cat_id); // <-------------------- not defined...
});
});

如您所知,jQuery 已弃用了以前的使用类型 $.ajax,新模式如上所示,位于 done() 函数中的上述代码中,我如何访问cat_id?在done()函数中,$(this)不再被识别,cat_id也不再被识别......

在 jQuery 引入 done() 之前,我们可以轻松访问发送的数据,因为我们使用的是 success: 并且我们仍然可以通过 ajax 函数访问发送的数据.

最佳答案

在您的示例中,您仍然可以在完成函数中访问cat_id,因为它仍在范围内。如果您需要访问 $(this),您需要将其绑定(bind)到完成回调,如下所示:

$('#blah').on('click', function(){
var cat_id = $(this).attr('id');
$.ajax({
// stuff...
data: {cat_id: cat_id}, // <--------------------
// stuff...
}).done(function(){
alert(cat_id); // alerts 'blah'
alert($(this).attr('id')); // also alerts 'blah'
}.bind(this)); // NOTICE THIS
});

关于jquery - $.ajax() 访问 did() 中发送的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15157693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com