Ajax 在不刷新的情况下提交时显示消息


Ajax display msg on submit without refresh

我正在通过 Ajax 提交表单数据,并希望在成功提交时在表单上方显示一条消息。

目前,表单确实成功发送了数据。它应该按照我的配置中的定义在表单提交<?php $this->renderFeedbackMessages(); ?>上呈现反馈消息.php

我哪里出错了?由于第一次使用 mvc,可能以错误的顺序做事?

我的配置.php文件我定义了以下内容;

define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");

我的模型;

public function addIsbn($isbn)
{
    // insert query here  
    $count =  $query->rowCount();
        if ($count == 1) {
            $_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
    return true;
        } else {
            $_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
    }
    // default return
    return false;
}

我的控制器;

function addIsbn()  
{
    // $_POST info here
    header('location: ' . URL . 'admin/searchIsbn');
}

我的搜索ISBN.php;

<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
       event.preventDefault();
       var isbn = $('#isbn_search').val();
       var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
        $.getJSON(url,function(data){
            $.each(data.items, function(entryIndex, entry){  
                $('#result').html('');
                var html = '<div class="result">';  
                html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
                html += '<hr><button type="button" id="add" name="add">add to library</button></div>';  
                $(html).hide().appendTo('#result').fadeIn(1000);
                $('#add').click(function(ev) {
                    $.ajax({
                         type: 'POST',
                         url: '<?php echo URL; ?>admin/addIsbn',
                         data: {
                             'isbn' : isbn   
                         }      
                    });
                });
            });
        });
 });
</script>

无控制台错误消息。

您在此处重定向:

header('location: ' . URL . 'admin/addIsbn');

删除它。

在此处回显成功消息,并将其添加到 HTML 元素的.html() API 中。

您的页面将不会刷新。

您的页面正在调用admin/addIsbn,该调用被重定向到admin/searchIsbn 。因此,您已经将renderFeedbackMessages()的输出发送到您的函数。

使用 success 回调将结果输出到页面:

$.ajax({
  type: 'POST',
  url: '<?php echo URL; ?>admin/addIsbn',
  data: {
    'isbn' : isbn   
  },
  success: function(data) {
    $('#result').html(data);
  }
});
<</div> div class="answers">

我能让它工作的唯一方法是向我的 Ajax 成功函数添加自动刷新,如下所示;

window.location.reload(true);

然而,工作对建议持开放态度。