我有一个包含项目列表的页面。我希望能够编辑这些项目。为了实现这一点,我在每个项目中都包含了一个编辑按钮。单击编辑按钮时,我使用jquery / AJAX来获取编辑表单。
这很好用。然而,一旦填写了表单(具有id =“object-create”),我再次想要使用AJAX将更改发布到我保存它们的后端。
AJAX POST
$('#object-create').on('submit', function(event){
event.preventDefault();
var myform = document.getElementById('object-create');
var fd = new FormData(myform );
var post_url = $(this).attr('action');
$.ajax({
url : post_url,
data : fd,
cache: false,
processData: false,
contentType: false,
type : "POST",
success : function(data) {
$('#result-container').html(data)
},
error : function() {
alert("error")
}
});
});
但是这不起作用,因为我的表单上的jquery事件永远不会触发。
当我简单地将表单硬编码到我的页面时,事件就会触发,当我在浏览器的Inspector中查看时,我看到
旁边有一个'ev'符号<form enctype="multipart/form-data" action="some_url/" method="post" id="object-create"> 'ev'
当我通过AJAX GET请求附加此表单时,不存在。我猜我必须(重新)将事件绑定到插入的表单,但我不知道如何。我该怎么做呢?
答案 0 :(得分:1)
您似乎正在向表单添加提交事件。
相反,在表单中添加一个按钮,(按钮类型按钮)它有助于与您不想做的事情保持一致,为按钮添加事件并将按钮ID设置为button1 。从此按钮内调用您的脚本。表格不应再提交。
以下是我可以深入了解的一个例子。
<!DOCTYPE html>
<html>
<head>
<title>ajax form submit</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<!-- GOOGLE JQUERY JS v3.2.1 JS !-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
</style>
</head>
<body>
<script>
// Loads before document ready...
$(document).on('click', '#button1', function(e) {
ajaxPost();
// Blur button1 for aesthetic reasons.
$('#button1').blur();
});
$(document).ready(function() {
console.log('1. Document is ready.');
// Run the App.
runApplication();
});
// We create a variable called runApplication and assign it a function runApplication()
var runApplication = function runApplication() {
console.log('1.0 runApplication() function called.');
// ajax Post.
ajaxPost();
};
/* Main AJAX function */
function ajaxPost() {
console.log('1.1 ajaxPost() function called.');
//var data = $('#form1').serializeArray();
console.log('2. Encode #form1 set of elements as a Serialized Array of objects (Names & Values)');
// Serialized Array of objects from #form1.
// Simulation purposes ONLY.
var data = [{
"name": "client_id",
"value": "111"
},
{
"name": "project_id",
"value": "222"
},
{
"name": "user_id",
"value": "465605"
}
];
// data: Serialized Array of objects (Names & Values).
console.log(data);
console.log('3. Stringify this Serialized Array of objects (Names & Values)');
// Stringify Serialized Array of objects.
data = JSON.stringify(data);
// data: Stringifyed Serialized Array of objects.
console.log(data);
console.log('3.1 data is now Valid JSON (RFC 4627).');
console.log('3.2 data to be sent is of type: ' + typeof data);
console.log('3.3 data is now ready for AJAX request.');
$.ajax({
url: 'php_pdo_mysql_insert.php', // url to post request to.
method: 'POST', // method of request. POST & GET
contentType: "application/json; charset=utf-8", // contentType is the type of data you're sending, so application/json; charset=utf-8 for JSON
dataType: 'text', // dataType is what you're expecting back from the server: json, html, text.
data: data, // data to send. Use encodeURIComponent(data) whenever you want to send "problematic" characters in the URL such as &, % etc. The opposite is decodeURIComponent.
timeout: 5000, // Longer than 5 seconds? HTTP SERVER or PHP Offline.***
// AJAX beforeSend event...
beforeSend: function() {
console.log('4. Ajax beforeSend* event fired.');
},
// AJAX success event...
success: function(data, textStatus, jqXHR) {
console.log('4.1 Ajax success* event fired.');
console.log('4.2 data received is of type: ' + typeof data);
// If data return 1 = Successful Insert Query
if (data === 1) {
console.log('Status: MySQL Insert Successful.');
}
// If data return 2 = Database Connection refused
if (data === 2) {
console.log('Status: MySQL Connection Refused.');
}
},
// AJAX error event...
error: function(jqXHR, textStatus, errorThrown) {
// If http server and/or PHP is/are offline...
if (errorThrown === 'timeout') {
console.log('5. Ajax error* event fired.');
console.log('5.1 Ajax errorThrown* timeout* of 5 seconds reached.');
console.log('5.2 Status: NGINX or PHP offline?');
}
}
// AJAX done event...
}).done(function() {
console.log('4.3 Ajax done* event fired.'); // Fired ONLY on success event fire.
// AJAX fail event...
}).fail(function() {
console.log('5.3 Ajax fail* event fired.'); // Fired ONLY on error event fire.
});
} // END ajaxPost()
// Loads before document ready...
$(document).on('click', '#button1', function(e) {
// Cancel the default action (navigation) of the click.
e.preventDefault();
// Call ajaxPost() function..
ajaxPost();
// Blur button1 for aesthetic reasons.
$('#button1').blur();
});
</script>
<form id="form1">
Client ID: <input type="text" name="client_id" value="111">
<br> Project ID: <input type="text" name="project_id" value="222">
<br> User ID: <input type="text" name="user_id" value="465605">
<p>
<button type="button" id="button1" ">button1</button>
</form>
Check Web Console <strong>Ctrl + Shift + K</strong>
</body>
</html>
答案 1 :(得分:1)
根据我的理解,当页面最初加载时,您的表单不存在,并且您在页面加载后动态创建表单。
将$('#object-create').on('submit', function(event){
更改为$(document).on('submit', '#object-create', function(event){
。有关详细信息,请阅读event propagation上的此部分。
旁注:只需执行
即可简化代码$(document).on('submit', '#object-create', function (event){
event.preventDefault();
// "this" is your form
var fd = new FormData(this);
var post_url = this.action;
// etc
});