In the front-end development, often use ajax interface to back-end data get returned, several ajax callback summary of frequently asked questions for your reference climb pit.
- Undefined contentType, may cause garbled data passed in the background, you can add the following code in ajax request
contentType:'application/json;charset=UTF-8',
- Good agreement reached back and return the data type of the background, the general definition json type.
JSON.stringify():将一个JavaScript值(对象或者数组)转换为一个 JSON字符串
JSON.parse():将一个 JSON 字符串转换为对象
Both are commonly used json api conversion
- In the success or error correction, return is get value, even if changing the async: false can not get to see the example below:
function checkUserTask(taskid){
$.ajax({
method:'get',
url:URL.checkUserTask,
async:false,
data:{'id':taskid},
success:(response)=>{
console.dir(response)
if(response.code==200 ){
return true;
}else{
return false;
}
}
});
}
Even if such an approach is success or failure, when calling checkUserTask methods are returned undefined, get true or false identity, it is generally written by the following:
function checkUserTask(taskid){
var flag = false;
$.ajax({
method:'get',
url:URL.checkUserTask,
async:false,
data:{'id':taskid},
success:(response)=>{
if(response.code==200 ){
flag = true;
}else{
flag = false;
}
}
});
return flag;
}
Behind the return of the callback can get the return value.