[英]Using JQuery and AJAX to pass data to a PHP script
I have an HTML form that Is only composed of a button with a value. 我有一个HTML表单,它仅由带有值的按钮组成。 I would like to leave it this way. 我想这样离开。 I am using AJAX/JQuery to pass the form data to a PHP script. 我正在使用AJAX / JQuery将表单数据传递给PHP脚本。 But, for some reason, the button value is not sent. 但是,由于某种原因,未发送按钮值。 What could I be doing wrong? 我可能做错了什么?
HTML: HTML:
<form id="friend-send" method="post" action="">
<button type="submit" class="foll" name="approve-friend" value="4"> Approve </button>
</form>
AJAX/JQUERY: AJAX / JQUERY:
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = $this.serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});
JQuery won't serialize a button, use a hidden field instead jQuery不会序列化按钮,而是使用隐藏字段
<form id="friend-send" method="post" action="">
<input type="hidden" name="approve-friend" value="4" />
<button type="submit" class="foll"> Approve </button>
</form>
Also, You need to serialze the form by id, not the button by id Instead of this 另外,您需要按ID序列化表单,而不按ID序列化按钮
$("#friend-request-buttons")
It should be this 应该是这个
$("#friend-send")
Lastly, since you are using ajax to post, you can simplfy your form open tag to this... 最后,由于您正在使用ajax进行发布,因此可以将表单打开标记简化为此...
<form id="friend-send">
<button>
tags are not supported by serialize https://api.jquery.com/serialize/ 序列化https://api.jquery.com/serialize/不支持<button>
标记
You would need to use an input of some kind. 您将需要使用某种输入。 A hidden one would work. 一个隐藏的人会起作用。
Don't use serialize
, create the input data yourself: 不要使用serialize
,自己创建输入数据:
var dataString = {};
var $button = $this.find("[type=submit]");
dataString[$button.attr('name')] = $button.val();
When you provide an object as the data:
argument to $.ajax
, jQuery will serialize it automatically. 当您提供$.ajax
的data:
参数作为对象时,jQuery会自动对其进行序列化。
This answer would be if you are set on using the button alone 如果您仅设置使用按钮,那么答案就是
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = "?" + $(this).find('button').attr('name') + "=" + $(this).find('button').attr('value');
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.