javascript - PHP Ajax 调用导航到表单提交上的操作页面

标签 javascript php jquery ajax

我的 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/

相关文章:

javascript - 显示加载 GIF 并在脚本加载后删除

javascript - 使用数组在 javascript 中获取输入值

php - if/else if/else 与数据库查询结果为 false。

php - 无法将变量 'sql_mode' 设置为“REPLACE”的值

javascript - 单击 td 行时获取 td 值。 MVC

javascript - 如何一个接一个地执行 jquery 函数(以及其他几个问题)

javascript - 表单相互重叠,如何默认隐藏表单并在 html、css 中单击时可见

javascript - Mongoose :为什么我没有收到错误响应

javascript - 如何在查询外部 django View 时刷新部分 DOM HTML

php - [PHP]编辑记录,更新mysql查询