简体   繁体   English

从对象运行jQuery Ajax

[英]Running jQuery Ajax from Object

My site is working pretty slow, what I have done is that I have a textarea that I want to get auto-saved to in the database. 我的网站运行非常缓慢,我所做的是我有一个要自动保存到数据库中的文本区域。 I am doing jQuery Ajax calls to auto-save the textarea content. 我正在执行jQuery Ajax调用以自动保存textarea内容。

My event on the textarea is the following: 我在textarea上的活动如下:

$(document).on('keyup','#notepad',function(e) {
    var text = $(this).val();
    Api.request({ handler: 'user', action: 'notepad', text: text });
});

The problem is that if I fast type "Hello World!", then it will be lagging due to the 12 needed ajax calls. 问题是,如果我快速键入“ Hello World!”,则由于需要12个ajax调用而将滞后。

I have in that case tried to use the abort() method in jQuery Ajax, but it doesn't seems to work, as none of the calls actually gets cancelled. 在那种情况下,我尝试在jQuery Ajax中使用abort()方法,但是它似乎不起作用,因为实际上没有取消任何调用。

My code is the following: 我的代码如下:

function Api(){
    this.current = $.ajax();
    this.request = function(options, apiCallback){
        // default arguments
        options = typeof options !== 'undefined' ? options : {};
        apiCallback = typeof apiCallback !== 'undefined' ? apiCallback : function(){};

        this.current.abort();
        this.current = $.ajax({
            type: 'POST',
            url: "api?"+new Date().getTime(),
            data: options,
            dataType: 'json',
            async: false
        })
        .done(function(data) {
            apiCallback(data);
        })
        .fail(function() {
            apiCallback({status: 'FAILED'});
        })
    };
}
var Api = new Api();

Does anyone have any idea how I can do this using a Javascript Object? 有谁知道如何使用Javascript对象做到这一点?

You can check the last time the user typed, if time is up to 5 seconds, make an Ajax call ? 您可以检查用户上次键入的时间,如果时间最多为5秒,请拨打Ajax电话?
EDIT: Or just use a setInterval to save the textarea text using Ajax each X second ;) 编辑:或只是使用setInterval每隔X秒使用Ajax保存textarea文本;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM