我正在加载一个表单作为 AJAX 请求的 json 输出。
以下 PHP 构成显示表单的请求的 JSON 输出:
$this->errors[] = "<form id='confirmreset' name='confirm_reset' action='" . URL .
"login/forgotPassword_action' method='post'><input type='hidden' name='user_email' value='" .
$this->user_email . "'> Email already registered. <input type='submit'
value='Click here for a PIN reminder'></form>";
然后,我也希望能够将此表单作为 AJAX 表单提交,但由于它未在 DOM 中加载,因此我的 jquery 似乎没有引用它。有什么想法吗?
这是到目前为止的代码:
$("#confirmreset").on("submit",function(event){
//disable default click operation
event.preventDefault();
var action_url = $(this).attr("action");
alert_box_register("Resetting password...");
console.log(action_url);
var postData = $(this).serializeArray();
console.log(postData);
$.post(action_url,postData,function(data){
console.log(data);
var obj = $.parseJSON(data);
alert_box_register(obj.message);
});
});
使用 .on()
由于元素是动态添加的,因此您无法将事件直接绑定到它们。因此,您必须使用事件委派。
$(document).on('submit','#confirmreset',function(event){ ..code here.. }
语法
$( elements ).on( events, selector, data, handler );
这应该像将第二个请求放入第一个请求的成功函数中一样简单。