在實際項目中,我們常會看到類似下面的 Ajax 代碼:
$.ajax({
url: 'EmailExist.action',
data: '{email:"' + email + '"}',
type: 'post',
dataType: 'json',
contentType: 'application/json; charset=utf8',
cache: false,
success: function(data) {
if (data.d) {
setTimeout(function() {
$('#tip_email').removeClass('validation-valid');
$('#tip_email').addClass('validation-error');
$('#tip_email').html('郵箱<strong>"' + email + '</strong>"已存在,請使用其他郵箱');
}, 10);
}
},
error: function(xhr) {
$('#tip_email').html(xhr.responseText);
}
});
很多人會困惑:這裡的 data.d 到底是什麼?
原來,d 是 ASP.NET WebService 返回的 JSON 對象的屬性,它包含了你 return 返回的內容,其餘所有數據都被放在這個 d 屬性裡面。所以在 success 回調中,要判斷或讀取服務端返回的實際結果,就得透過 data.d 來訪問。