如何在完成AJAX过程之前防止所有链接重定向

时间:2016-03-28 14:35:15

标签: javascript ajax tinymce

我有一个使用tinyMCE的应用程序。在此页面中,用户将撰写一条消息,然后在另一页面上预览(不使用tinyMCE的预览)。我目前有一个AJAX函数,可以在用户点击tinyMCE UI时保存内容。问题是,我在同一页面上有不同类型的链接,有时当用户点击链接时,AJAX功能无法在重定向之前保存内容,从而导致空白预览或未保存的消息。

<div>
<textarea id='msg'></textarea>
<a id='preview'>Preview</a>
<a id='other_page'>Other Page</a>
<a id='another_page'>Another Page</a>
</div>

以下是JavaScript处理程序和函数。

    <script>
    // INITIALIZE TINYMCE
    tinyMCE.init({
    // SAVE CONTENT ON BLUR
            editor.on('blur', function() { save_message(this); });
    })

    function save_message(){
        var msg= tinyMCE.get('msg ').getContent();
         $.ajax({
                    statusCode : { 404: function(){alert('Not Found');} },
                    type       : 'post',
                    data       : {msg:msg},
                    url        : '<script_that_handles_save>',
                    success    : function(res){ // DO SOMETHING } 
            }); 
    }

// WHEN PREVIEW IS CLICKED
$('a.preview).click(function(){
          save_message();
});

$('a.other_page).click(function(){
          save_message();
});

$('a.another_page).click(function(){
          save_message();
});
</script>

2 个答案:

答案 0 :(得分:1)

您可以创建某种标志变量,它将告知是否应该阻止链接重定向。在发送保存消息的AJAX请求之前,请将此变量设置为true,并在成功请求后将其设置回false。还要在所有链接上设置一个事件监听器,它将检查此标志变量,如果它等于true,则阻止重定向。

示例代码:

var linksDisabled = false;

function save_message() {
  linksDisabled = true;
  $.ajax({
    success: function() {
      linksDisabled = false;
    }
    // some other options
  })
}

$("a").click(function(event) {
  if (linksDisabled) {
    event.preventDefault();
  }
});

答案 1 :(得分:1)

有些事情,您的save_message()函数是一个AJAX调用,需要完成并发回一个响应才能工作。单击锚标记时,将调用该函数(根据上面的代码),但在函数返回响应之前页面会重定向。 此外,您似乎为每个锚标记冗余调用该函数,为什么不为所有锚标记调用一次,如a.click(function(){ // your function here });

您的代码逻辑很好,您只需重新构建和简化它,就像这样:

tinyMCE.init({
// SAVE CONTENT ON BLUR
        editor.on('blur', function() { save_message(this); });
})
$('a').click(function(e){
        // prevent the redirect
        e.preventDefault();
       var msg= tinyMCE.get('msg ').getContent();
       var location = $(this).attr('href');  
      // execute ajax
     $.ajax({
                statusCode : { 404: function(){alert('Not Found');} },
                type       : 'post',
                data       : {msg:msg},
                url        : '<script_that_handles_save>',
                success    : function(res){
                               // redirect on success
                              window.location.href = location
                         }
        });
});