Jquery 不从 html 表单中收集信息

Jquery not collecting info from an html form

本文关键字:信息 表单 不从 html Jquery      更新时间:2023-09-26

我正在尝试使用jquery来运行php文件。php 将一些信息发送到数据库。

php 本身是有效的。我可以删除js代码,所有内容都发送到数据库。从我的数据库可以明显看出发生了什么。未收集表单中的内容。有些东西会进入数据库,但不会进入表单中的信息。

这是我的代码,可能有什么问题?

// submit without refresh
$(function() {
    $('#form').submit(function(e) {
        // Stop the form actually posting
        e.preventDefault();
        // Send the request
        $.post('submit.php', {}, function(d) {
            console.log(d);
            // Here we handle the response from the script
            // We are just going to alert the result for now
            alert(d);
        });
    });
});

我的表单有id="form" 为什么 js 不收集表单信息?

您不能以这种方式发布表单。 $.post 将不知道表单的元素,除非您告诉它要发送什么。为了使上面的代码正常工作,您必须将表单的数据传递给$.post,例如:

$.post('submit.php',
    data: { <your form data here> },
    success: function(data){
        console.log(data);
    }
);

您需要将字段值传递给 php 脚本:

$.post('submit.php', {data: $(this).serialize()}, function(d) {
       console.log(d);
       // Here we handle the response from the script
       // We are just going to alert the result for now
       alert(d);
});

您必须先获取表单数据。序列化用于获取表单数据。

$(function() {
 $('#form').submit(function(e) {
    var data = $(this).serialize(); // get the form datas
    // Stop the form actually posting
    e.preventDefault();
    // Send the request
    $.post('submit.php', data, function(d) {
        console.log(d);
        // Here we handle the response from the script
        // We are just going to alert the result for now
        alert(d);
    });
});

});

发送数据的最佳方法是 ajax 方法,如下所示:

var nameVar = $("#name").val();
var loc = $("#location").val();
$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: nameVar, location: loc
})
.done(function( msg ) {
    alert( "Data Saved: " + msg );
});