[英]Post data via jQuery AJAX
I'm trying to post data to my table using AJAX, I have the following form, 我正在尝试使用AJAX将数据发布到表中,我具有以下格式,
<form>
Total <input type="text" id="total" name="total" /><br />
Bill name<input type="text" id="bill-name" name="bill-name" /><br />
bill descriptiion <input type="text" id="bill-description" name="bill-description" /><br />
bill colour<input type="text" id="bill-colour" name="bill-colour" />
<input type="button" value="submit" onClick="insertBill();" />
</form>
And my AJAX code is as... 我的AJAX代码是...
<script type="text/javascript">
function insertBill()
{
var bill = $("#bill").val();
$.post('insert_bill.php', {total: total, bill-name: bill-name, bill-description: bill-description, bill-colour: bill-colour}, function(data)
{
$("#bills").html(data);
});
}
</script>
For some reason however my values aren't being passed. 但是由于某种原因,我的价值观没有得到通过。 I'm new to AJAX and so I've been following a tutorial so excuse my naivety!
我是AJAX的新手,所以我一直在关注教程,所以请原谅我! How do I make this work?
我该如何工作?
For this and so many other PHP, jQuery ajax problems, I highly recommend serialize try this: 对于这个以及其他许多PHP,jQuery ajax问题,我强烈建议序列化尝试一下:
<div id="bills"></div>
<script type="text/javascript">
function insertBill()
{
$.post('insert_bill.php', $('form').serialize(),
function(data) {
$("#bills").html(data);
});
}
Your javascript variables haven't been defined yet. 您的javascript变量尚未定义。 Your javascript function doesn't know about the form.
您的javascript函数不了解表单。
Try something like this: 尝试这样的事情:
$.post('insert_bill.php', {total: $('#total').val(), bill-name: $('#bill-name').val()...
Or you can set your variables beforehand 或者您可以预先设置变量
<script type="text/javascript">
function insertBill()
{
var total = $('#total').val();
I'm not sure what this is doing though: 我不确定这是怎么做的:
var bill = $("#bill").val();
I don't see any id="bill" 我没有看到任何id =“ bill”
You are passing variables that are not even defined. 您正在传递甚至没有定义的变量。 You need to define all your post variables like you did with
var bill = $("#bill").val();
您需要像使用
var bill = $("#bill").val();
一样定义所有发布变量var bill = $("#bill").val();
and then pass them. 然后通过
I would recommend you to use this jQuery plugin that does everything for you. 我建议您使用此 jQuery插件为您做所有的事情。 I use it and it works fine.
我用它,它工作正常。
Change your form
tag to this(or something similar) 将
form
标签更改为此(或类似内容)
<form id="bill" onsubmit="return insertBill();">
and in your function, do this: 然后在您的函数中执行以下操作:
<script type="text/javascript">
function insertBill() {
var bill = $("#bill").val();
$.post('insert_bill.php', {total: total, bill-name: bill-name, bill-description: bill-description, bill-colour: bill-colour}, function(data)
{
$("#bills").html(data);
} );
return true; // So that form may proceed.
}
</script>
忽略缺少的值, bill-name
不是有效的标识符,如果您真的想使用bill-name
,则应将其包装在引号中,并使用jQuerys val()
检索值:
$.post('insert_bill.php',{ 'bill-name' : $('#bill-name').val() } ....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.