gpt4 book ai didi

javascript - RequireJS Ajax 被调用过多

转载 作者:行者123 更新时间:2023-11-28 09:00:04 25 4
gpt4 key购买 nike

在rails服务器上运行,当我通过提交表单进行ajax调用时,表单会经过3次。这张图显示了 3 次失败,但是无论失败还是成功,都会运行 3 次。 enter image description here

当我拿走时:

require(['/assets/monitor/monitor'], function(Monitor){
var monitor = new Monitor();
monitor.initial();
});

它完全停止工作。当我只带走时:

var monitor = new Monitor();
monitor.initial();

它进行 1 个 ajax 调用。

为什么当我没有调用监视器文件的实例时,ajax 仍然被调用?

main.js

requirejs.config({
baseUrl: './',
paths: {
'jquery': '/assets/monitor/lib/jquery-1.10.2.min',
'jquery-ui': '/assets/jquery-ui-1.10.2.custom.min',
'async': '/assets/monitor/lib/async',
'bootstrap': '/assets/monitor/lib/bootstrap',
'underscore': '/assets/monitor/lib/underscore',
'datatables': '/assets/monitor/lib/jquery.dataTables.min',
'DT_bootstrap': '/assets/monitor/lib/DT_bootstrap'
},
shim: {
'jquery': {
exports: '$'
},
'async': {
exports:'async'
},
'bootstrap': {
deps: ['jquery']
},
'underscore': {
exports: '_'
},
'datatables': {
deps: ['jquery']
},
'DT_bootstrap': {
deps: ['datatables']
}
}
});
require(['/assets/monitor/monitor'], function(Monitor){
var monitor = new Monitor();
monitor.initial();
});

monitor.js

define(['jquery', 'async', 'bootstrap'], function($, async, jQuery) {

var Monitor = function() {};
// Kicks off the file
Monitor.prototype.initial = function () {
var hostname = 'http://somehostthatworks';
var portNumber = 'some port that works';
var contentType = 'JSON';
var versionNumber = '1.1';
this.receiveMonitor(hostname, portNumber, contentType, versionNumber);
};
...
Monitor.prototype.recieveMonitor = function(hostname, portNumber, contentType, versionNumber) {
$("form").submit(function () {
//Some ajax that works when form is submitted.
});
};
...
});

application.js

// Call requireJS and main.js
//= require ./monitor/lib/require
//= require ./monitor/main

最佳答案

通过将对 require.js 和 main.js 的调用移出 application.js 并移至我需要它们的页面(好的调用是 monitor.html.erb),我能够停止重复。

monitor.html.erb

...
<% @stylesheetIncludes= ["bootstrap.min", "jquery-ui-1.10.2.custom.min", "monitor", "jquery.dataTables.min"] %>
<% @javascriptIncludes= ["monitor/lib/require", "monitor/main"] %>
<!-- Monitor Service -->
<%= render 'monitor/monitorService' %>
...

关于javascript - RequireJS Ajax 被调用过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17871197/

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