Javascript Jquery未从html表单收集信息
我正在尝试使用jquery运行一个php文件。php向数据库发送一些信息 php本身可以工作。我可以删除js代码,所有内容都发送到数据库。从我的数据库中可以明显看出发生了什么。未收集表单中的内容。有些东西会进入数据库,但不是表单中的信息 这是我的代码,有什么问题吗Javascript Jquery未从html表单收集信息,javascript,jquery,html,forms,Javascript,Jquery,Html,Forms,我正在尝试使用jquery运行一个php文件。php向数据库发送一些信息 php本身可以工作。我可以删除js代码,所有内容都发送到数据库。从我的数据库中可以明显看出发生了什么。未收集表单中的内容。有些东西会进入数据库,但不是表单中的信息 这是我的代码,有什么问题吗 // submit without refresh $(function() { $('#form').submit(function(e) { // Stop the form actually posti
// 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不收集表单信息?您需要将字段值传递给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);
});
您必须首先获取表单数据。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);
});
});
})) 您不能以这种方式发布表单。$。除非您告诉post要发送什么,否则post将不知道表单的元素。要使上述代码正常工作,必须将表单的数据传递到$.post,例如:
$.post('submit.php',
data: { <your form data here> },
success: function(data){
console.log(data);
}
);
$.post('submit.php',
数据:{},
成功:功能(数据){
控制台日志(数据);
}
);
发送数据的最佳方法是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 );
});
您从表单中获取数据的确切位置?您没有将任何值发布到服务器,而是将emtpy对象作为数据传递到
POST
请求。您仍然需要序列化表单的数据并传递它。这篇文章可能是重复的。@codebarker,这不是重复的。我的意思是我以前没有自己发布过。m90我如何序列化它?那么我如何让name从字段中获取信息呢?我可以把它做成name:$('#name').val(),
?为什么这个方法是最好的,你能多评论一下吗?通过这样做,可以发现禁用javascript时没有默认的回退。是的,您可以或在调用ajax之前,您可以将所有字段值存储在不同的变量中,并替换为name:namevar。您可以解释一下为什么您认为此方法最好吗?我现在更新我的答案,您可以应用此方法,您如何才能接受正确的答案?答案不是错误的,但不是完全完美的,因为大多数情况下使用json方法发送或接收数据,这通常是通过带有post/get的ajax调用方法完成的,这是一种完美的方法,或者您需要像下面的检查一样调用xml: