我在确定如何将变量传递给ajaxForm()
函数的参数时遇到了问题。我点击jQuery中的表单按钮后从隐藏的表单字段获取模板化路径(这很好用)我可以将它传递给其他函数但不传递给ajaxForm()
参数:
var templatedir;
// Get variable of templatedir
$('form#contact input[type="submit"]').on('click',function(){
templatedir = $('input[name=templatedir]').fieldValue();
});
// Validate Form
function validateform(formData, jqForm, options) {
...
// IF I CALL TEMPLATEDIR HERE IT WORKS
}
// Send to PHPMailer
$("form#contact").ajaxForm({
url: templatedir, // IT DOESNT WORK HERE
type: 'post',
beforeSubmit: validateform,
target: '#msg',
clearForm: true
});
我尝试了这个答案(How do i pass variables between functions in javascript)的解决方案,但是它没有用。
答案 0 :(得分:0)
您的变量templatedir
未定义。
您应该在点击活动中致电ajaxForm()
。
$('form#contact input[type="submit"]').on('click',function(event) {
event.preventDefault();
// Send to PHPMailer
$("form#contact").ajaxForm({
url: $('input[name=templatedir]').fieldValue(),
type: 'post',
beforeSubmit: validateform,
target: '#msg',
clearForm: true
});
});
答案 1 :(得分:0)
兴趣点是:
将templatedir = $('input[name=templatedir]').fieldValue();
更改为
templatedir = $('input [name = templatedir]')。val();
url: templatedir, // IT DOESNT WORK HERE
并在表单提交之前将其设置为validateform:我的片段:
var templatedir;
$(function () {
$('form#contact input[type="submit"]').on('click', function(){
templatedir = $('input[name=templatedir]').val();
});
function validateform(formData, jqForm, options) {
// because you now are in the beforesubmit event
// you can change the url.....
options.url = templatedir;
}
$("form#contact").ajaxForm({
type: 'post',
beforeSubmit: validateform,
target: '#msg',
clearForm: true
});
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://malsup.github.io/jquery.form.js"></script>
<form id="contact" action="www.google.com" method="post">
templatedir: <input type="text" name="templatedir"/>
<input type="submit" value="Submit Comment" />
</form>
<div id="msg"></div>