在不超出页面的情况下更新数据库

Updating DB without going outside the page

本文关键字:情况下 更新 数据库      更新时间:2023-09-26

我正在尝试弄清楚如何在提交表单时触发更新,而无需实际离开页面。 我知道使用JavaScript是可能的,我一直在试图弄清楚如何。

现在,表单由两部分组成,即Reg.php和Update.php

Reg.php是:

    <form action="update.php" method="post">
        <div class="input-group">
            <span class="input-group-addon">Title:    </span>
            <input type="text" class="form-control" placeholder="title" name="title"><br/>
        </div>
        <div class="input-group">
            <span class="input-group-addon">Content</span>
            <textarea class="form-control" rows="3" name="desc"></textarea></br>
            <!--<input type="text" class="form-control" placeholder="desc" name="desc">-->
        </div>
        <div class="input-group">
            <span class="input-group-addon">Push</span>
            <input type="text" class="form-control" placeholder="push" name="push"><br/>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Send</button>
    </form>

和更新.php是:

<?php
    require 'connection.php';
    $sql="INSERT INTO `newsUpdate` (`title` ,`desc` ,`pushContent`) VALUES ('$_POST[title]','$_POST[desc]','$_POST[push]')";
    if (!mysqli_query($con,$sql))
    {
        die('Error: ' . mysqli_error($con));
    }
    echo "1 record added";
?>

所以(自然地),在表单发送详细信息后,我在新页面上收到"添加了 1 条记录"通知(update.php),但相反 - 我希望在"Reg.php"上完成所有操作,包括状态报告(错误/添加了 1 条记录)

我尝试创建一个基本的 JS 脚本并触发它单击按钮

function loadXMLDoc()
    {
        var xmlhttp;
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("POST","update.php",true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send();
    }
</script>

但这是在黑暗中的真实镜头——它没有奏效。

谁能指出我正确的方向?(阅读手册除外)。

看起来你快到了;你只需要表示你想要在XHR请求中发送什么数据(通过将字符串传递给send()方法。

function createPostString(form) {
    var str = '';
    for (var i=0;i<form.elements.length;i++) {
        var curr = form.elements[i];
        str += encodeURIComponent(curr.name) + '=' + encodeURIComponent(curr.value) + '&';
    }
    return str;
}

然后将xmlhttp.send()更改为xmlhttp.send(createPostString(document.getElementsByTagName("form")[0]));(或您想要选择表单的方式)。

您尚未在代码中包含点击处理程序,但请确保以return false;结束处理程序,以停止通过传统 HTTP POST 提交页面。

您还可以添加一个完整的处理程序,以便在 AJAX 请求完成后执行某些操作;

xmlhttp.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
        // do something with this.responseText.
    } 
};

当你用jquery标记你的问题时,如果你想沿着这条路走下去,你可以使用;

$('button[type="submit"]').on('click', function (e) {
    e.preventDefault();
    jQuery.post("update.php", $('form').serialize()).done(function (data) {
        // Do something when the request has completed...
    });
});