我正在使用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.
});
});
});