Some problems encountered and solutions
Preface
In our study and work, we will always encounter some problems. If we do not summarize and record, we will soon forget,,,
1. Reasons and solutions for the inability to assign values to variables in jquery ajax
We are using JQuery's Ajax to extract data from the background and want to assign it to a global variable, but it can't be assigned. Why?
The reason is actually very simple. The Ajax we use is an asynchronous operation, which means that the data has not been extracted when you assign it, of course you can’t assign it, so just change it to a synchronous operation.
Solution:
Change asynchronous to synchronous, as follows, add async: false, it can be assigned
var user = null
$.ajax({
url: "/user/findByName",
type: "get",
dataType: "json",
async: false,
data: {
name:name
},
success:function (data){
if (data.data.user!=null){
user = data.data.user
}
}
})
2. Convert the date to the specified format
Add the following method to the Date prototype
Date.prototype.format = function(fmt) {
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt)) {
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}
After adding, we can call like this
var time = new Date().format("yyyy-MM-dd hh:mm:ss");
console.log(time1);
Can also be called like this
var time1 = new Date().format("yyyy-MM-dd");
console.log(time1);
3. Invalid solution for the node that jQuery uses append to add cannot add events
Sometimes our events in the newly added elements fail. The reason is that when we initialize the event, we don't have these newly added elements, so we cannot bind the event.
To do this, we need the on method in jQuery to bind events. The corresponding event cannot be added directly, take the click event as an example
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("div").on("click","p",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>This is a new paragraph.</p>").insertAfter("button");
});
});
</script>
</head>
<body>
<div style="background-color:yellow">
<p>This is a paragraph.</p>
<p>Click any p element to make it disappear. Including this one.</p>
<button>Insert a new p element after this button</button>
</div>
</body>
</html>