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

格西奥

使用此功能

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

这样,根本不做任何事情:

      $( 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]);
    };
  }

它进入for循环(我可以登录控制台modepins[i],它们正在工作),但似乎未调用该函数。控制台不显示任何内容。

有办法解决吗?谢谢

CodeGodie

使用回调函数没有错,但是您确实错过了几件事。您忘记了调用initMode函数,它mode应该是您提到的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>

这是我创建FIDDLE,以便您可以看到它的工作原理。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章