繁体   English   中英

如何递归调用Ajax函数

[英]How to call Ajax function recursively

我想知道如何递归调用Ajax函数。 我的ajax代码是这样的,

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
  var step='1';
  $.ajax
  (

   {   
    url: 'test1.php',
    data: {step: step},        
    success: function(output) 
    {                                         
       step=eval(output);
       alert(step);
    }
   }
  );

</script>
</head>   
</html>

和PHP代码是这样的

<?php
 function writeName()
 {
  echo "step=2";
 }
 function ReadName()
 {
  echo "In Read Name Function";
 }
 if(isset($_REQUEST['step']) && !empty($_REQUEST['step']))
 {
  $step = $_REQUEST['step'];
  switch($step)
  {
   case '1' : 
    writeName();
    break;
   case '2' : 
    ReadName();
    break;
   default  : 
    echo "Empty String";   
  }
 }
?>

第一次调用此函数时,step变量的值等于1,而Function Write名称将其修改为2。现在,我想调用Step变量值等于2的Ajax函数。这样就调用了第二个php函数。

您可以创建一个函数来进行Ajax调用并接受该步骤作为参数:

function getStep(step) {
  $.ajax
    (
     {   
      url: 'test1.php',
      data: {step: step},        
      success: function(output) 
      {                                         
         step=parseInt(output);
         alert(step);
         if (step < 2) {
            getStep(step);
         }
      }
     }
    );
}

您需要在服务器端PHP脚本中使用“ json_encode()”函数,而不是简单的“ echo”。 Javascript中的“ eval()”方法尝试运行返回的文本。

您应该在writeName()函数中编写以下代码:

echo json_encode(2);

暂无
暂无

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

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