if / else语句在AJAX响应函数中不起作用

时间:2012-01-03 10:56:15

标签: jquery ajax

我在这里完全被迷惑了。在我开始之前,我应该说我的所有代码都是100%工作,这个问题出现的原因并不明显。

当用户单击按钮时进行AJAX调用,并且如果满足条件则返回表单。然后,当用户提交表单时,如果满足条件,它将再次进行AJAX调用并提交数据。数据成功提交,并返回“成功”或“错误_1”,“错误_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_wordsmax_wordssuccess - 所以为什么if语句不能正常工作? 控制台中没有错误,正如我所说的那样,除响应之外都有效。

3 个答案:

答案 0 :(得分:1)

有两种逻辑可能性:if语句不起作用,或者它们内部的代码不起作用。尝试在大括号内放一个alert或其他东西,看看会发生什么!

答案 1 :(得分:1)

我在Firebug调试过程中发现了一些非常奇怪的东西。

我的PHP文件中的一些注释被附加到响应文本中。

确保您使用中间PHP文件来处理该文件中没有这些<!--之类的评论的请求。

答案 2 :(得分:0)

您需要使用

吗?
response.responseText

而不是

response

条件?

-Vinay