我需要扩展 jQuery(作为插件)。问题是,$.ajax
不在范围内工作,$.extend
但在范围外工作正常。我jQuery 3.4.1
在我的项目中使用。
我的代码:
(function($) {
jQuery.extend({
mmw: function(options) {
var settings = $.extend({
mtarget: "#cnapp-mmw",
imgSize: "square",
imgRestricted: true,
imgtype: ["gif", "png", "jpg", "jpeg", "pdf"]
}, options);
$.ajax({
type: "GET",
url: "http://example.com/public/get-media",
dataType: "html",
success: function(data) {
alert(data);
},
error: function(e) {
alert(e); // Showing this as outout [object Object]
}
});
}
})
})
但这显示了正确的输出:
(function($) {
$.ajax({
type: "GET",
url: "http://example.com/public/get-media",
dataType: "html",
success: function(data) {
alert(data); // This is showing the proper output
},
error: function(e) {
alert(e);
}
});
jQuery.extend({
mmw: function(options) {
var settings = $.extend({
mtarget: "#cnapp-mmw",
imgSize: "square",
imgRestricted: true,
imgtype: ["gif", "png", "jpg", "jpeg", "pdf"]
}, options);
}
})
})
我的第一个代码有什么问题?jQuery 3 有什么不同吗?
请注意,我需要在没有选择器的情况下调用这个插件
$(".trigger").on('click', function(){
$.mmw();
});
这$.extend
是必须的功能吗?我们将不胜感激地收到有关最佳实践的任何建议。
更新
经过多次调试,我发现 AJAX 请求在任何块或事件中都不起作用。我将它与Codeigniter 4 (beta 4)
.
这显示错误
$(".trigger").on('click', function(){
$.ajax({
type: "GET",
url: "http://example.com/public/get-media",
dataType: "html",
success: function(data){ alert("Ok"); },
error: function(e){ alert(JSON.stringify(e)); } // Showing error message {"readyState":0,"status":0,"statusText":"TypeError: Cannot read property 'open' of undefined"}
});
});
但这显示了正确的数据
$.ajax({
type: "GET",
url: "<?=base_url('test/'.session_id())?>",
dataType: "html",
success: function(data){ alert(data); }, // Showing the Data
error: function(e){ alert(JSON.stringify(e)); }
});
$(".trigger").on('click', function(){
});
意味着 Ajax 功能仅在范围之外工作。真的很困惑。