if/else语句不能在AJAX响应函数中工作
我在这里完全困惑。在我开始之前,我应该说我所有的代码都是100%的工作,而这个问题似乎没有明显的原因。if/else语句不能在AJAX响应函数中工作
当用户点击一个按钮时会产生一个AJAX调用,并且如果满足条件则返回一个表单。然后,当用户提交表单时,如果满足条件,则会再次进行AJAX调用并提交数据。数据提交成功,并返回'成功'或'error_1','error_2'等。
什么是不工作只是JS中的响应函数中的if/else语句。
这里是PHP回调函数:
function submit_entry() {
// my variables
if($current_words > $max_words) {
echo 'max_words';
} elseif($current_words < $min_words) {
echo 'min_words';
} else {
$post_data = array(
'ID' => $entryID,
'post_date' => date('YmdHis'),
'post_content' => $text,
'post_status' => 'publish'
);
wp_update_post($post_data);
echo 'success';
}
exit;
}
这里是AJAX调用:
jQuery('#entrySubmit').click(function() {
jQuery.post(
MyAjax.ajaxurl,
{
action : 'submit-entry',
etc.
},
function(response) {
if(response == 'max_words') {
jQuery('#add_entry_error').html('You exceeded the maximum number of words.');
} else if(response == 'min_words') {
jQuery('#add_entry_error').html('You have not written enough words, please write more.');
} else if(response == 'success') {
jQuery('#add_entry_step_1').slideUp();
jQuery('#add_entry_step_2').slideDown();
jQuery('#add_entry_error').html('');
}
jQuery('#add_entry_error').append(response);
}
);
});
这里jQuery('#add_entry_error').append(response);
线成功追加要么min_words
,max_words
,或者success
- 那么,为什么不if语句工作? 控制台中没有错误,正如我所说的,除了响应之外,它都可以工作。
有两种逻辑可能性:if
语句不工作,或者其中的代码不起作用。尝试将一个alert
或其他东西放在大括号中,看看会发生什么!
我在使用'alert'时得到了预期的响应,就好像if语句只是拒绝工作一样。 – 2012-01-03 11:06:08
不,我的意思是把警报放在“if”后面的部分。如果你也得到了预期的回应,那么它不能是if语句 – Nicolas78 2012-01-03 13:51:00
你需要使用的
response.responseText
代替
response
在条件
?
-Vinay
刚刚尝试过,返回'undefined' – 2012-01-03 11:12:43
在Firebug调试过程中,我发现了一些非常奇怪的东西。
这是我的PHP文件中被附加到响应文本中的一些注释。
确保您是否使用中间PHP文件来处理在该文件中没有像这些<!--
这样的注释的请求。
您是否检查过是否输入了ifs?你是否尝试过调试,或者至少在那里发出警报?您是否检查过响应之前或之后是否没有空白? – GolezTrol 2012-01-03 11:01:14
尝试提醒你的回应,看看你得到了什么 – Kishore 2012-01-03 11:01:39
当我使用'alert'时,我得到了预期的回应,就好像if语句只是拒绝工作。 – 2012-01-03 11:06:33