0

私は外部のjavascriptファイルにAjax関数を持っています:

ajax.js

function webservice(x){

   jQuery.ajax
            ({
                //some code here
            });

  Data = function(data){
                    if(x==1)
                            {
                                for(i=0;i<10;i++)
                                {
                                     webservice(i);
                                alert"Onload");
                                }
                            }
                            else 
                            if(x==5)
                            {
                                for(i=0;i<10;i++)
                                {
                                webservice(i);
                                alert ("Onclick");
                                }
                            }

        }

私は次のような別のhtmlページを持っています:

webservice.html

 <html>
 <title>Call web service</title>
 <head>
 <script type="text/Javascript" src="jquery-1.9.1.js"></script>
 <script type = "text/javascript" src="ajax.js"></script>
 <script>

 window.onload=function()
 {
   webservice(1)('onload');    //call 1 

 }

 </script>
 </head>

  <body>


  <input id="webservice"  type = "button" name = "webservice" value = "Call Webservice"       
  onclick="webservice(5)"/>


  </body>
  </html>

そこで、onLoadとonclick of buttonで同じ関数を呼び出して、両方の呼び出しが同時に実行されるようにします。しかし、onloadがたとえば3回実行され、ボタンをクリックすると、onloadが停止し、onclickが実行されます。onclickも実行し、onloadを4回目の反復から開始したいのですが、両方ともアラートを同時にまたは1つずつ表示する必要があります。助けてください。前もって感謝します。

他の方法も歓迎します。

4

1 に答える 1

0

$.ajax非同期関数だからです。現在のバージョンでは、AJAX呼び出しが終了する前にコードが呼び出される可能性があります。したがって、あなたは奇妙な振る舞いをします。

これを修正するには、コードを次のように成功コールバックに移動する必要があります。

function webservice(x) {
    var inputParam = x;
    jQuery.ajax({
        url: 'test.php',
        data: {},
        success: function (data) {
            if (inputParam  == 1) {
                for (i = 0; i < 10; i++) {
                    webservice(i);
                    alert("Onload");
                }
            } else if (inputParam  == 5) {
                for (i = 0; i < 10; i++) {
                    webservice(i);
                    alert("Onclick");
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('an error occurred!');
        }
    });
}

さらに、インラインJSは避けてください。

交換

window.onload=function()
 {
   webservice(1)('onload');    //call 1 
 }

$(document).ready(function(){
    webservice(1);//call 1 
});

  <input id="webservice"  type = "button" name = "webservice" value = "Call Webservice"       
  onclick="webservice(5)"/>

$('#webservice').click(function(){
    webservice(5);
});
于 2013-03-20T07:08:27.193 に答える