【发布时间】:2017-02-22 10:16:04
【问题描述】:
所以我有一些东西可能看起来有点小,但就是这样。
这一切都是使用 jQuery 完成的
我有一个函数“cont_refresh”,用于刷新页面内容等,其中包含一个 AJAX 请求,用于将变量传递给外部文档/脚本进行处理。
除此之外,我还有一个匿名函数,应该在表单提交时触发......这意味着完全不相关,不应该在按下此按钮时发生。
然而,当我运行“cont_refresh”时,提交功能被触发,它似乎触发提交功能的点是我开始发出我的 ajax 请求。
最终发生的事情是我发出 ajax 请求,一个只在服务器上运行一个函数,第二个是提交我的表单......我不希望后者发生。
有两个按钮分别处理这两个事情,一个是提交按钮,另一个是与此问题相关的不是提交按钮。
为什么?以及如何防止这种情况发生?
你的脑海中会盘旋着一个问题,为什么这个小丑有两个功能基本上做同样的事情,但这是另一个主题,我会优雅地请求你提出一个新的帖子;)。
/*
This is what I want to run... it does but fails then.....(see below this function)
*/
function cont_refresh(form,params,url,e,modal){
$(".ng-loading-container").toggleClass("ng-loading-container-show");
if(modal === 'undefined'){
modal = false;
}
var request = $.ajax({
method: 'post',
url: url,
data: params,
success: function(result){
if(e !== '' && e !== 'undefined'){
$(e).html(result);
} else {
alert('Success');
}
},
error: function(){
alert('Page Error')
$(".ng-loading-container").toggleClass("ng-loading-container-show");
},
}).fail(function() {
alert( "Something went wrong!" );
$(".ng-loading-container").toggleClass("ng-loading-container-show");
})
// end of cont_refresh()
}
/*
.... This runs. Which is not my intention!
*/
$('form').submit(function (e){
e.preventDefault();
submit_form(e.target);
// there is an additional function that handles any submition from this point but have not included it as .
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rightly or wrongly the intention here is to run a stored SQL procudure.<br>
<p>The reason the statements are stored in the db is so anyone (with access) can add and edit these statements or functions from my front end application.</p>
<form role="form" action="myscript.php" method="post">
<input type="hidden" name="stp_tsk_id" id="stp_tsk_id" class="form-control" value="34">
<div class="form-group col-md-12">
<label for="stp_function">Function (SQL statement)</label>
<textarea class="form-control" name="stp_function" id="stp_function" rows="3">SELECT * FROM SOME_TABLE</textarea>
</div>
<!-- this button should trigger only the function it is calling onclick -->
<button role="button"
class="btn btn-default btn-md"
onclick="cont_refresh('',{'id':34},'app/handlers/process_steps.php')">
Run this Step
</button>
<!-- There is a second "submit" button but not relevent for this query -->
<button role="submit" class="btn btn-default btn-md">Save</button>
</form>
【问题讨论】:
-
使用 e.preventDefault();其中 e 是事件处理程序
标签: php jquery ajax forms submit