0

アプリには2つのjavascript/jquery関数があります。常にrefresh()関数があり、データベースからデータを取得してフロントエンドビューを再描画します。

方法の1つは、PHP関数にデータを送信することです。これにより、MySQLデータベースに簡単に挿入し、2番目に編集します。ここでは、次のようになります(同じなので、1つだけ投稿します)。

function insertedit()
{
$('.res').each(function()
{
    $.post("/controller/method/",{id: id},function(data,status,xhr)
    {
        if(status=="success")
        {
        }
    })
});     

refresh();
}

この関数を使用してデータを挿入しようとすると、すべて正常に機能し、ビューが非同期で再描画されますが、それを使用してデータを編集しようとすると、ページを更新して更新されたビューを表示する必要があります。編集操作は挿入よりも時間がかかると思います。SQLからデータを取得する更新関数は古いデータ(削除されていないレコード)を取得するだけです。どうすれば修正できますか?

編集

$(function()
{
 refresh();
});



function insertedit(){
  var $promises = [];
  $('.res').each(function()
  {

    $promises.push(
    $.post("/controller/metgod/",{id, id},function(data,status,xhr)
    {
        if(status=="success")
        {
        }
    })
    );
});     

$.when.apply($, $promises).then(function() {
    refresh();
});
}
4

2 に答える 2

4

約束を使用する

function insertedit()
{
  var $promises = [];

  $('.res').each(function(id){
    var $this = $(this);

    $promises.push(
      $.post("/controller/method/", {'id': $this.attr('id')}, function(data,status,xhr){
        $this.text(data); // success
      })
    );
  });

  $.when.apply($, $promises).then(function(){
    refresh();
  });     
}

ここでフィドルを参照してください、それはhttp://jsfiddle.net/69eMp/4/で動作します

于 2012-12-29T02:04:21.140 に答える
2

私はある時点でそのようなソリューションを使用しました、そしてここに私のソリューションがありました(ここにライブデモがあります):

/**
 * Class that will handle delayed function calls
 * @param fn     the funciton to call
 * @param ctx    the context to use as 'this' inside the function
 * @param delay  delay in millis
 */
var AsyncCall= function(fn, ctx, delay) {
   var timer = null;

   ctx   = ctx || window;
   delay = delay || 1;

   return function() {
       // prevent calling the delayed function multiple times
       if (timer) clearTimeout(timer);

       var args = arguments;

       timer = setTimeout(function() {
          timer = null;
          fn.apply(ctx, args);
       }, delay);
   };
};

// wrap the 'refresh' funciton inside the async call object with a 200 millis delay
var refreshAsync = new AsyncCall(refresh, null, 200);

function insertedit()
{
$('.res').each(function()
{
    $.post("/controller/method/",{id: id},function(data,status,xhr)
    {
        if(status=="success")
        {
        }

        // schedule calling 'refresh'
        refreshAsync();
    })
});
}

これが好まれる理由は、すべてのAjaxリクエストを更新する必要がないためです。これにより、refresh毎回更新する場合よりも関数の実行回数が少なくなります。また、200ミリ秒はそれほど長くはありませんが、Ajax呼び出しが戻るには十分であり、ユーザーには気づかれません。

于 2012-12-29T01:42:36.163 に答える