I encountered a small problem today while maintaining a project. But I think this question is very helpful for the project. Write it down to help everyone. First let's look at a piece of code
$(".search").click(function(){ $.ajax({ type:"get", url:"/communitys/CommunityShowController?method=listByAllCondition", dataType:"json", contentType: "application/x-www-form-urlencoded; charset=utf-8", data: { school: school, grade: grade, type: type }, success: function(data){ var showId = data[0].communityShowId; if(showId == 0){ $("#list").html("No corresponding society"); }else{ $("#list").html(''); var list = ''; var data1 = data; $.each(data1, function (index, item) { //loop to get data list += "<li><a href='/communitys/CommunityShowController?method=toEnter&communityShowId="+ item.communityShowId +"'><div class='img-box'><img src='/communitys/backpages/image/"+item.logo+"'></div><p class='img-cap'>"+item.name+"</p></a></li>"; }); $(list).appendTo("#list"); } } }); });
This is a piece of code I'm learning and maintaining. The meaning is that when I click search, when there is content corresponding to the request, I will display a picture, and when there is no content, I will display a sentence " No corresponding community ".
This is already working code, the difference from my previous code is that I didn't set the datatype
Second
if(showId == 0){ //I wrote this statement as if(data == '[{"communityShowId":"0","logo":"",name:""}]'){
My original intention was to let data parse this json data directly, but since I didn't set the datatype, the array made of this json was parsed into a string. In this way, the statement below the if cannot be executed at all.
And when I set the datatype, ajax parses this string into json data format that matches my content. Second I set
var showId = data[0].communityShowId;
This is equivalent to my parsing showId is to parse the json data of data, and I regard the json data of data as an array, each key will correspond to a key value, and I get showId as the first key in this json . When showId==0, that is, when the key value is 0, the if statement will be returned!