同时调用ajax函数onload和onclick

Calling ajax function onload and onclick simultaneously

本文关键字:onload onclick 函数 ajax 调用      更新时间:2023-09-26

我在外部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的按钮中调用相同的函数,这样两个调用将同时运行。但是当onload运行例如说3次,我点击按钮,然后onload停止和onclick运行。我想onclick也运行和加载从第四次迭代开始,两者都应该同时显示警报或1乘1。所以请帮帮我。提前谢谢。

因为$.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);
});