我正在将 jQuery 用于我拥有的一个小项目,这是我第一次使用它。将我所有的 UI 代码放入其中是否安全$(document).ready()
?我基本上是在创建一个在按下按钮时弹出的表单,并通过 AJAX 处理该表单。基本上,当我将 AJAX 功能与控制 UI 的功能分开时,AJAX 不起作用。但是,当我将它们都放入时$(document).ready()
,一切正常。这是我的代码。请忽略我的评论,因为它们是出于学习目的。
$(document).ready(function(){ //ready for DOM manipulation
/*FORM UI*/
var container_form=$('#container_form'); //container form box
var addButton=$('.addButton'); //"+" add button
container_form.hide(); //initially hides form
$(addButton).click(function(){
$(container_form).toggle('fast');
/*SUBMISSION AJAX*/
$('form.ajax').on('submit',function() { //Make form with class "ajax" a JQuery object
var that = $(this), //"that"-current form, "url"-php file, "type"-post, "data"-empty object for now
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){ //search all elements in the form with the attribute "name"
var that=$(this), //legal attribute
name=that.attr('name'); //name of the legal attribute
value=that.val(); //value of text field in legal attribute
data[name]=value; //data object is filled with text inputs
});
$.ajax({
url: url, //url of form
type: type, //type of form
data: data, //data object generated in previous
success: function(response){ //reponse handler for php
if(!response){
console.log("Error");
}
console.log(response);
}
});
return false; //Stops submission from going to external php page.
});
});
});