Jquery Ajax调用未在for循环中执行

时间:2022-08-26 11:14:59

Using this function

使用此功能

  function readPinMode(callback,pin){
     $.ajax({
        type: 'GET',
        url: path,
        data: {
        'funct': "readPinMode", //function included and working ou of loops
        'pin': pin,
        'php': 0
     },
     success: function (result) {
        //console.log(result);
        callback(result);
     },
        error: function (xhr, textStatus, error) {
        console.log(xhr);
        console.log(textStatus);
        console.log(error);
    }
   });
 };

in this way, simply does not do nothing:

通过这种方式,根本不做任何事情:

      $( document ).ready(function() {
  <?php
  $js_array = json_encode($GLOBALS['gpio']); // got from included file, working
  echo "var pins = ". $js_array . ";\n";
  ?>
  console.log( "Document ready." );
  for (i = 0; i < pins.length; i++) {
        var mode = "m" + pins[i];
        function initMode(){
        readPinMode(function(ret){
        console.log(ret);
        $(mode).text(ret);
        console.log(mode);
      }, pins[i]);
    };
  }

It enters the for loop (I can log in console mode and pins[i], they are working) but the function seems to not be called. Console does not show anything.

它进入for循环(我可以登录控制台模式和引脚[i],它们正在工作)但是函数似乎没有被调用。控制台没有显示任何内容。

Is there a way to solve this? Thanks

有办法解决这个问题吗?谢谢

3 个解决方案

#1


1  

There's nothing wrong with using callback functions, however you did miss a couple of things. You are forgetting to call your initMode function and mode should be an ID like you mentioned:

使用回调函数没有任何问题,但是你确实错过了很多东西。您忘记调用initMode函数,模式应该是您提到的ID:

<script>
    function readPinMode(callback, pin) {
        $.ajax({
            type: 'GET',
            url: 'SGWEB/header.php',
            data: {
                'funct': "readPinMode", //function included and working ou of loops
                'pin': pin,
                'php': 0
            },
            success: function (result) {
                callback(result);
            },
            error: function (xhr, textStatus, error) {
                console.log(error);
            }
        });
    }

    function initMode(mode, pin) {
        readPinMode(function (ret) {
            $(mode).text(ret);
        }, pin);
    }

    $(document).ready(function () {
        var pins = <?= json_encode($GLOBALS['gpio']) ?>;
        for (i = 0; i < pins.length; i++) {
            var mode = "#m" + pins[i];
            initMode(mode, pins[i]);
        }
    });
</script>

Here's a FIDDLE I created so that you can see how it works.

这是我创建的一个FIDDLE,以便您可以看到它是如何工作的。

#2


3  

I suggest to not use a real loop which needs a proper closure, but instead run again in the success

我建议不要使用需要正确关闭的真实循环,而是在成功中再次运行

<?php
  $js_array = json_encode($GLOBALS['gpio']); // got from included file,  working
  echo "var pins = ". $js_array . ";\n";
?>
var cnt = 0;
function readPinMode(){
  if (cnt>=pins.length) return;      
  $.ajax({
    type: 'GET',
    url: path,
    data: {
    'funct': "readPinMode", //function included and working ou of loops
    'pin': pins[cnt],
    'php': 0
   },
   success: function (result) {
      //console.log(result);
      $("#mode").append(result)
      cnt++;
      readPinMode();
   },
   error: function (xhr, textStatus, error) {
    console.log(xhr);
    console.log(textStatus);
    console.log(error);
   }
 });
}
$(function() { readPinMode(); }); 

Proof of concept:

概念证明:

var pins = ["pin1", "pin2", "pin3"];
var cnt = 0;

function readPinMode() {
  if (cnt >= pins.length) return;

  document.write('<br/>pin:' + pins[cnt]); // your Ajax

  cnt++;
  readPinMode();
}
$(function() {
  readPinMode();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

#3


0  

I think its syntax error, Try this code

我认为它的语法错误,请尝试此代码

console.log( "Document ready." );
  for (i = 0; i < pins.length; i++) {
        var mode = "m" + pins[i];       
        readPinMode(function(ret){
        console.log(ret);
        $(mode).text(ret);
        console.log(mode);
      }, pins[i]);       
  }

I removed the function initMode() as it creates same function definition over and over again which overrides the exiting function, and its all messy. You should not define a function inisde a loop as the final function will be of the last loop. Also there is no need for you to define the function inside a loop in this scenario.

我删除了函数initMode(),因为它一遍又一遍地创建相同的函数定义,它会覆盖exiting函数,而且它的所有内容都很混乱。你不应该定义一个函数inisde一个循环,因为最后一个函数将是最后一个循环。此情况下,您无需在循环内定义函数。

Here is a Working Prototype Fiddle

这是一个工作原型小提琴

#1


1  

There's nothing wrong with using callback functions, however you did miss a couple of things. You are forgetting to call your initMode function and mode should be an ID like you mentioned:

使用回调函数没有任何问题,但是你确实错过了很多东西。您忘记调用initMode函数,模式应该是您提到的ID:

<script>
    function readPinMode(callback, pin) {
        $.ajax({
            type: 'GET',
            url: 'SGWEB/header.php',
            data: {
                'funct': "readPinMode", //function included and working ou of loops
                'pin': pin,
                'php': 0
            },
            success: function (result) {
                callback(result);
            },
            error: function (xhr, textStatus, error) {
                console.log(error);
            }
        });
    }

    function initMode(mode, pin) {
        readPinMode(function (ret) {
            $(mode).text(ret);
        }, pin);
    }

    $(document).ready(function () {
        var pins = <?= json_encode($GLOBALS['gpio']) ?>;
        for (i = 0; i < pins.length; i++) {
            var mode = "#m" + pins[i];
            initMode(mode, pins[i]);
        }
    });
</script>

Here's a FIDDLE I created so that you can see how it works.

这是我创建的一个FIDDLE,以便您可以看到它是如何工作的。

#2


3  

I suggest to not use a real loop which needs a proper closure, but instead run again in the success

我建议不要使用需要正确关闭的真实循环,而是在成功中再次运行

<?php
  $js_array = json_encode($GLOBALS['gpio']); // got from included file,  working
  echo "var pins = ". $js_array . ";\n";
?>
var cnt = 0;
function readPinMode(){
  if (cnt>=pins.length) return;      
  $.ajax({
    type: 'GET',
    url: path,
    data: {
    'funct': "readPinMode", //function included and working ou of loops
    'pin': pins[cnt],
    'php': 0
   },
   success: function (result) {
      //console.log(result);
      $("#mode").append(result)
      cnt++;
      readPinMode();
   },
   error: function (xhr, textStatus, error) {
    console.log(xhr);
    console.log(textStatus);
    console.log(error);
   }
 });
}
$(function() { readPinMode(); }); 

Proof of concept:

概念证明:

var pins = ["pin1", "pin2", "pin3"];
var cnt = 0;

function readPinMode() {
  if (cnt >= pins.length) return;

  document.write('<br/>pin:' + pins[cnt]); // your Ajax

  cnt++;
  readPinMode();
}
$(function() {
  readPinMode();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

#3


0  

I think its syntax error, Try this code

我认为它的语法错误,请尝试此代码

console.log( "Document ready." );
  for (i = 0; i < pins.length; i++) {
        var mode = "m" + pins[i];       
        readPinMode(function(ret){
        console.log(ret);
        $(mode).text(ret);
        console.log(mode);
      }, pins[i]);       
  }

I removed the function initMode() as it creates same function definition over and over again which overrides the exiting function, and its all messy. You should not define a function inisde a loop as the final function will be of the last loop. Also there is no need for you to define the function inside a loop in this scenario.

我删除了函数initMode(),因为它一遍又一遍地创建相同的函数定义,它会覆盖exiting函数,而且它的所有内容都很混乱。你不应该定义一个函数inisde一个循环,因为最后一个函数将是最后一个循环。此情况下,您无需在循环内定义函数。

Here is a Working Prototype Fiddle

这是一个工作原型小提琴