【问题标题】:Return a result after ajax callajax调用后返回结果
【发布时间】:2015-07-08 17:24:04
【问题描述】:

我一直在尝试使用 ajax 编写一个小函数,但我真的很纠结如何返回结果。我在这里看到了一些示例,但我没有设法将它们应用到我的代码中......

//function to detect bespoke page
function PageR(iURL) {
  var theLink;
   $.ajax({
      url: './BSK_'+iURL+'.php', //look to see if bespoke page exists
      success: function(data){
        theLink = ('./BSK_'+iURL+'.php'); //if it does display that page
      },
      error: function(data){
          theLink = ('./'+iURL+'.php'); //if it doesn't display the standard page
      },

    }); //end $.ajax
    return theLink;
};

我希望能够返回theLink以将其存储为变量以执行以下操作...

function Nav() {
  var theLink = PageR(nav_newCust);
  $.mobile.changePage(theLink);
};

请帮忙!!

【问题讨论】:

    标签: jquery ajax jquery-mobile jquery-mobile-ajax


    【解决方案1】:

    你为什么不试试这样的:

    //function to detect bespoke page
    function PageR(iURL, callback) {
      var theLink;
       $.ajax({
          url: './BSK_'+iURL+'.php', //look to see if bespoke page exists
          success: function(data){
            theLink = ('./BSK_'+iURL+'.php'); //if it does display that page
          },
          error: function(data){
              theLink = ('./'+iURL+'.php'); //if it doesn't display the standard page
          },
          complete: function(){
             callback(theLink);
          }
        }); //end $.ajax
    };
    
    function Nav() {
      PageR(nav_newCust, $.mobile.changePage);
    };
    

    【讨论】:

      【解决方案2】:

      你不能这样做,因为你有非阻塞的 ajax 调用,而且 PageR 函数总是返回 undefined。

      试试这个:

      function PageR(iURL) {
         $.ajax({
            url: './BSK_'+iURL+'.php',
            success: function(data) {
              $.mobile.changePage ('./BSK_'+iURL+'.php');
            },
            error: function(data){
                $.mobile.changePage ('./'+iURL+'.php');
            },
          });
      };

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-20
        • 2011-07-13
        • 1970-01-01
        • 2016-02-05
        • 1970-01-01
        • 2021-05-15
        • 2018-01-09
        • 2018-09-14
        相关资源
        最近更新 更多