Jquery没有从html表单中收集信息

时间:2013-10-14 06:09:00

标签: javascript jquery html forms

我正在尝试使用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 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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);
});

答案 2 :(得分:0)

您必须先获取表单数据。 Serialize用于获取表单数据。

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

});

答案 3 :(得分: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 );
});
相关问题