如何在不离开页面的情况下将表单插入mysql(javascript + html)

时间:2016-05-09 16:49:19

标签: javascript ajax

我试图将新用户插入mysql。我曾尝试使用jQuery,但它似乎并没有起作用。我尝试使用纯JavaScript,但它是一样的。单击按钮后没有响应。怎么了?

var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);

function submitForm() {

    var acR = document.getElementById("ac2");
    var pw1 = document.getElementById("pw1");
    var shop = document.getElementById("shop");

    var http = new XMLHttpRequest();
    http.open("POST", "http://xyz.php", true);
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
    http.send(params);
    http.onload = function() {
        alert(http.responseText);
    };
}

2 个答案:

答案 0 :(得分:1)

你的JS代码中存在很多问题,我在这里整理了它并在本地运行到一个名为xyz.php的页面,这样就可以让AJAX调用工作但你需要发布您的PHP代码以获得有关数据库查询的任何帮助

    var regBtn = document.getElementById("regBtn");
    regBtn.addEventListener("click", submitForm, false);

    function submitForm() {

        var acR = document.getElementById("ac2");
        var pw1 = document.getElementById("pw1");

        var http = new XMLHttpRequest();
        // removed the http:// protocol, assuming you're going for a local AJAX call
        http.open("POST", "xyz.php", true);
        http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        // get values of the form fields, don't submit the full element
        // also added the plus (+) character before the final pw1
        var params = "ac=" + acR.value + "&pw1=" + pw1.value;
        http.send(params);
        http.onload = function() {
            alert(http.responseText);
        }
    }

我附上了一个屏幕截图,显示Chrome Dev Tools愉快地记录成功的AJAX请求

chrome dev tools successfully logging ajax calls

答案 1 :(得分:0)

尝试使用JQuery帖子。

var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");

$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
   alert( "Data inserted: " + data );
});

后端处理此帖子,然后在NodeJs(express)中实现插入操作

app.post("/xyz", function(req, res, next) {
    var obj = {};
    obj[acR] = body.ac;
    obj[pw1] = body.pw1;
    mysql.insert(obj);

});