在不重新加载页面的情况下向 SQL 数据库发布数据

3
问题是我无法在不重新加载页面的情况下向数据库中插入数据。经过测试,没有使用note_sql.js时我的note_sql.php可以正常工作,但是js文件似乎存在问题。如果有人能给我指点方向,那就太好了。 Index.php
    <form id="noteform" action="note_sql.php" method="POST">
    <input type="text" name="note"></input>
    <input id="sub" type="submit" value="Save Note" />
    </form>
    <span id="result_note"><span>
   <script type ="text/javascript" src="jquery/note_sql.js"></script>

note_sql.js

$("#sub").click(function(){

var data = $("#noteform: input").serializeArray();
$.post($("#noteform").attr("action"),data,function(info){$("result_note").html(info); });
    clearInput();
}); 

$("#noteform").submit(function(){
    return false;
});

function clearInput(){
    $("#noteform :input").each(function(){
        $(this).val('');
    });
}

2
请使用 $("#noteform" ).submit(function( event ) { 代替 $("#sub").click(function(){ - Saty
1
也许这个链接有帮助:https://dev59.com/FWrWa4cB1Zd3GeqP6guE - Alex
1个回答

5

使用jQuery Ajax,以下是工作代码:

请将ID添加到“Note Form”元素:

<pre>
      <script>
            $(document).ready(function () {
                $("#sub").click(function () {

                    var name = $("#note").val();
                    var message = $("#message").val();

                    $.ajax({
                        type: "post",
                        url: "note_sql.php",
                        data: "name=" + name,
                        success: function (data) {
                            alert(data);
                        }

                    });

                });
            });
        </script>
</pre>

我尝试了上面的代码,但是我被重定向到note_sql.php。 - kunz
从表单操作中删除note_sql.php。 - Rajveer gangwar
好的,现在它可以工作了,但我不需要它在警告框中,它需要出现在一个<span id="result_note"><span>区域中。我该怎么做呢? - kunz
使用 $('span#result_note').html(data); 替代 alert(data);。 - Rajveer gangwar
感谢您的帮助,@rajveer,您非常出色。 - kunz
谢谢亲爱的@jake123 - Rajveer gangwar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接