我在我的body标签的开头声明了内联脚本中的函数。 然后在外部脚本中。在表单上提交。它会触发一个匿名函数 ,它处理表单中的数据并提交$ .ajax方法。在文件末尾调用外部脚本无法从外部脚本调用内嵌JavaScript函数
问题是我在表单标记中为函数名称指定了'data-success =“functionName”'。它会触发外部脚本中的功能。 但外部脚本不能识别html文件中调用的内联函数。
这里是一个例子。 https://jsfiddle.net/vsbmn8w1/?utm_source=website&utm_medium=embed&utm_campaign=vsbmn8w1
HTML
<script>
$(document).ready(function() {
// The Inline function that dont get called externally
function searchResult(data) {
alert()
}
});
</script>
<!-- Trigger On Submit -->
<form method="post" class="async-form" data-success="searchResult">
<button type="submit">submit</button>
</form>
外部脚本
$(document).ready(function() {
$(document).on("submit", "form.async-form", function(event) {
// Declare form in a variable
var $this = $(this);
// Prevent Page reloading
event.preventDefault();
// Collect Form parameters
var action = $this.prop('action');
var method = $this.prop('method');
var form = $this.serialize();
// Default request object
var request = {
url: action,
type: method,
data: form
};
// Adding parameter to the object if data exist
if (typeof $this.data('success') != 'undefined') {
request['success'] = $this.data('success');
}
if (typeof $this.data('error') != 'undefined') {
request['error'] = $this.data('error');
}
if (typeof $this.data('beforeSend') != 'undefined') {
request['beforeSend'] = $this.data('beforeSend');
}
if (typeof $this.data('complete') != 'undefined') {
request['complete'] = $this.data('complete');
}
// Finally make the ajax request
$.ajax(request);
})
});