我有一个问题,这是吹我的头脑:我如何发送存储在PHP变量的表单ID到我的AJAX脚本,使正确的表单得到更新提交?
我的表单是一个模板,当$_REQUEST['id']
设置时,从MySQL表加载数据。因此,我的表单可以为不同的行包含不同的数据。
那么if (isset($_REQUEST["eid"]) && $_REQUEST["eid"] > 0) { ... fill the form ... }
表单ID存储在PHP变量中,如$form_id = $_REQUEST["eid"];
然后,如果用户更改了任何内容,我想使用下面的按钮来更新表单:
<button type="submit" id="update" class="form-save-button" onclick="update_form();">UPDATE</button>
和以下AJAX将数据发送到update.php:
function update_form() {
var dataString = form.serialize() + '&page=update';
$.ajax({
url: 'obt_sp_submit.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: dataString, // serialize form data
cache: 'false',
beforeSend: function() {
alert.fadeOut();
update.html('Updating...'); // change submit button text
},
success: function(response) {
var response_brought = response.indexOf("completed");
if(response_brought != -1)
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn(); // fade in response data
$('#obt_sp')[0].reset.click(); // reset form
update.html('UPDATE'); // reset submit button text
}
else
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn();
update.html('UPDATE'); // reset submit button text
}
},
error: function(e) {
console.log(e)
}
});
}
我想添加表单的id到数据字符串,像这样:
var dataString = form.serialize() + '&id=form_id' + '&page=update';
但是我不知道怎么做。有人能帮帮我吗?
上面已经说过的最实际的方法是在表单中利用input type="hidden"
。这样的一个例子是:
<form action="#" method="post" id=""myform">
<input type="hidden" name="eid" value="1">
<input type="submit" value="Edit">
</form>
让您在jQuery中运行类似的内容:
$('#myform').on('submit', function(){
update_form();
return false;
});
如果您通过AJAX请求正确发送所需的内容(从需要的地方获取输入等等等等等等....)
您也可以将其包含在数据字符串中;我不太明白你为什么要……但各有各的。
var dataString = form.serialize() + "&eid=SOME_EID_HERE&page=update";
听起来像是type=hidden
表单字段的工作:
<input type="hidden" name="eid" value="whatever">
必须使用PHP动态编写字符串:
var dataString = form.serialize() + "&id='<?php echo $REQUEST['eid'] ?>'+&page=update";
在服务器端,您可以在文档上编写Php代码,它们将在客户端显示为HTML/JS。