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 比 1。所以请帮助我。提前致谢。

也欢迎任何替代方法。

4

1 回答 1

0

Because $.ajax is an asynchronous function. In your current version, your code is called potentially before the end of the AJAX call. Therefore, you have a wird behavior.

To fix that, your code must be moved into the success callback like this :

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!');
        }
    });
}

Furthermore, avoid inline JS.

Replace

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

By

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

And

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

By

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