我正在编写一个javascript函数,该函数应根据选择的案例更改明信片的视图。
我的问题是对象的旧值" m_case"正在使用。如果我按下按钮" case-btn"两次我在明信片视图中选择了正确的案例。但我想按下按钮一次就会触发它。
我想我必须在m_case.setCase()函数调用中执行类似回调函数的操作,但我无法使其正常工作,
$('.case-btn').on('click', function() {
remove_active_state_from_cases();
m_case.setCase($(this).data('case'));
// Changes the view of the postcard
m_postcard.changeBackground(m_case.getPhoto());
m_postcard.changeMessage(m_case.getMessageText());
m_postcard.changeFullName(m_case.getFullName());
m_postcard.changeCountry(m_case.getCountry());
$(this).toggleClass('active');
});
setCase()函数
this.setCase = function(id) {
// Set ID
this.setID(id);
var that = this;
$.ajax({
url: 'get_case_by_id.php',
type: 'get',
dataType: 'json',
data: {id: that.getID() },
success: function(data) {
if(data.success) {
that.setFirstName(data.first_name);
that.setFullName(data.full_name);
that.setAdress(data.adress);
that.setCountry(data.country);
that.setStamp(data.stamp);
that.setPhoto(data.photo);
that.setSummary(data.summary);
that.setStory(data.story);
that.setMessageText(data.message_text);
that.setDefaultMessageText(data.default_message_text);
that.setMessageImg(data.message_img);
} else {
console.log('failure');
}
}
编辑问题可能出在我的AJAX调用中,我必须等到调用ajax。但是当我的Ajax完成而不是之前我如何继续第一个流程?
解
我通过添加一个回调参数并在ajaxs complete函数中调用该函数来实现它。
$('.case-btn').on('click', function() {
remove_active_state_from_cases();
var that = this;
m_case.setCase($(this).data('case'), function() {
m_postcard.changeBackground(m_case.getPhoto());
m_postcard.changeMessage(m_case.getMessageText());
m_postcard.changeFullName(m_case.getFullName());
m_postcard.changeCountry(m_case.getCountry());
$(that).toggleClass('active');
});
});
// Sets the whole case from an id.
this.setCase = function(id, callback) {
// Set ID
this.setID(id);
var that = this;
$.ajax({
url: 'get_case_by_id.php',
type: 'get',
dataType: 'json',
data: {id: that.getID() },
success: function(data) {
if(data.success) {
that.setFirstName(data.first_name);
that.setFullName(data.full_name);
that.setAdress(data.adress);
that.setCountry(data.country);
that.setStamp(data.stamp);
that.setPhoto(data.photo);
that.setSummary(data.summary);
that.setStory(data.story);
that.setMessageText(data.message_text);
that.setDefaultMessageText(data.default_message_text);
that.setMessageImg(data.message_img);
} else {
console.log('fail big time');
}
},
complete: function() {
callback();
}
});
}
答案 0 :(得分:1)
您的m_postcard.changeBackground
和其他呼叫应该在success
回调中,或者在成功回调中调用的另一个函数中,因为在异步ajax调用完成之前不会设置这些值。
现在代码的方式为m_postcard.changeBackground
,并且在setCase
函数执行完毕后立即调用其他调用。这意味着您的方法在数据从服务器到达之前执行
当ajax正在处理时,您可能应该在屏幕上显示加载消息,让用户知道他们必须等到处理完成。在调用.ajax
调用之前显示消息,并在成功/错误回调中隐藏它。
网站内容的任何更改都应该从成功回调中完成,即更改active
州,更改内容等。