简体   繁体   English

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

[英]How to insert form into mysql without leaving the page (javascript+html)

I'm trying to insert a new user into mysql. 我正在尝试将新用户插入mysql。 I have tried to use jQuery, but it doesn't seem to be working. 我试图使用jQuery,但似乎无法正常工作。 I tried to use pure javascript, but it's the same. 我尝试使用纯javascript,但是相同。 It has no response after I click on the button. 单击按钮后无响应。 What's wrong? 怎么了?

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);
    };
}

There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php , so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries 您的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);
        }
    }

I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests 我已附上一个截屏,显示Chrome开发工具愉快地记录了成功的AJAX请求

chrome dev工具成功记录了ajax调用

Try to use a JQuery post. 尝试使用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 );
});

Backend handles this post and then implement the insert action for example in NodeJs(express) 后端处理此帖子,然后在NodeJs(express)中实现插入操作

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM