【问题标题】:How to return Jquery ajax call value?如何返回 Jquery ajax 调用值?
【发布时间】:2012-02-21 10:35:10
【问题描述】:

如何在调用 jquery ajax 的函数中返回值。我接近了以下方法,我不知道它是否正确

function a(){
var a=ajaxFunction();
}

$.ajax({
    url: "Handler.ashx",
    cache: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        _testId = data.Id;
    }

return _testId

});

但是在 var a 中,值是未定义的。使用上述方法不会返回 _testId 的值。如果是错误的,请告诉我正确的方法。

【问题讨论】:

    标签: jquery ajax call


    【解决方案1】:

    您需要使用回调函数,因为“Ajax”中的 A 代表“异步”。

    $.ajax({
        'url': 'Handler.ashx',
        'cache': false,
        'contentType': 'application/json; charset=utf-8',
        'dataType': 'json',
        'success': callback
    );
    
    function callback(data) {
      var testID = data.id;
      console.log(testID);
    }
    

    你也可以使用匿名函数来内联它:

    $.ajax({
        'url': 'Handler.ashx',
        'cache': false,
        'contentType': 'application/json; charset=utf-8',
        'dataType': 'json',
        'success': function(data) {
          var testID = data.id;
          console.log(testID);  
        }
    );
    

    所有依赖于 Ajax 结果的代码都应该在回调中处理。

    【讨论】:

      【解决方案2】:

      由于 AJAX 调用是异步运行的,return 语句将在调用完成之前被命中,因此返回的值始终是未定义的。

      您需要更改逻辑以仅在成功处理程序中处理 AJAX 调用的结果:

      $.ajax({
          url: "Handler.ashx",
          cache: false,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (data) {
              _testId = data.Id;
      
              // do whatever you need with _testId in here.
              // You can pass it to another function if you require to modularise your logic, eg.
              processResult(data)
          }
      });
      
      function processResult(json) {
          // do stuff with your json here
      }
      

      【讨论】:

        【解决方案3】:

        我可能会这样做:

        var _testID = false;
        
        function a(){
            ajaxFunction();
            if(_testID)
            {
                //Do what you need here
            }
        }
        
        $.ajax({
            url: "Handler.ashx",
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                _testId = data.Id;
            }
        });
        

        【讨论】:

          猜你喜欢
          • 2011-09-21
          • 2012-06-01
          • 2010-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-20
          • 1970-01-01
          • 2012-11-25
          相关资源
          最近更新 更多