我的 php 代码中有这个 ajax 调用,它仍然导航到操作页面。我希望 ajax 调用保留在同一页面上,并且只更新页面的一部分。我在这里做错了什么:
<form method="post" id="holderSave" action="student_add_scene.php">
<h3> Save to Holder</h3><br/>
<div id="cutfrom">
<input placeholder="Cut from" name="from" id="from">
<button href="#" onclick="captureElapsed('elapseFrom', 'from');
return false;">capture</button>
</div>
<div id="cutto">
<input placeholder="Cut to" name="to" id="to" >
<button href="#" onclick="captureElapsed('elapseTo', 'to');
return false">capture</button>
</div>
<div id="savecapt">
<input placeholder="add label" id="label" name="label"/>
<input type='submit' value='Save' class='button'>
</div>
</form>
<script>
$('#holderSave').on("submit", (function (e) { // catch the form's submit event
e.preventDefault();
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
var posting = $.post( url, { from: $('#from').val(), label:$('#label').val(), to: $('#to').val()});
posting.done(function(response)){
$('#holderSave').html(response); // update the DIV
alert(response);
}
});
return false;
}));
</script>
最佳答案
这是一个语法错误:
$.ajax({// create an AJAX call... var $form = $(this), url = $form.attr('action');
您似乎试图将传递给 ajax
的对象文字视为函数体。事实并非如此,因此您不能只在其中编写语句。
由于您稍后使用 $.post
发出 ajax 请求,因此 $.ajax
完全没有意义。删除该行,它应该可以工作。
固定代码。除了对 .ajax 毫无意义的半次调用之外,您还遇到了一堆语法错误,我在重新格式化它时已修复了这些错误。
使用浏览器的开发人员工具控制台。使用http://jshint.com/
// Remove pointless ( from before the second argument of the call to on().
$('#holderSave').on("submit", function(e) {
e.preventDefault();
// Remove half a call to .ajax
var $form = $(this),
url = $form.attr('action');
var posting = $.post(url, {
from: $('#from').val(),
label: $('#label').val(),
to: $('#to').val()
});
posting.done(function(response) {
$('#holderSave').html(response);
alert(response);
// Remove line with extra } here
});
return false;
// Remove extra ) here
});
关于javascript - PHP Ajax 调用导航到表单提交上的操作页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31557083/