0

我正在尝试使用 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不收集表单信息?

4

4 回答 4

1

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

$.post('submit.php',
    data: { <your form data here> },
    success: function(data){
        console.log(data);
    }
);
于 2013-10-14T06:20:11.383 回答
0

您需要将字段值传递给您的 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);
});
于 2013-10-14T06:17:53.403 回答
0

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

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

});

于 2013-10-14T06:19:26.973 回答
0

发送数据的最佳方式是 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 );
});
于 2013-10-14T06:45:48.600 回答