从函数中获取 ajax return

get ajax return from function

尝试从带有 when 调用的 ajax 调用中将 ajax 数据检索到 jquery 中的变量。但据我了解数据是未完成的 ajax 数据。在下面我无法访问 responseJSON 下的数据的地方以对象形式给出响应。

{readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function, …}

//jQuery 调用函数的代码 ajax

jQuery(document).ready(function() {
  var response = ajaxcall(); 
   console.log(response);
});

//函数

function ajaxcall(){
   return $.ajax({
        url: "url",
        type: "POST",
        data: form_data,
        dataType: 'json',
        contentType: false,
        cache: false,
        processData:false,
        beforeSend : function()
        {
        },
        success: function(data)
        {
            if(data=='invalid')
            {
                alert("invalid data");
            }
            else
            {
            // success
                return data;
            }
        },
        error: function(e) 
        {
        }          
    });

}

是的,因为 ajax 调用是异步的。所以你必须传递一个回调函数或使用承诺或使用 jquery.when

1.Use $.when

$(document).ready(function() {
  $.when(ajaxcall()).then(response=>{
    console.log(response)
  })
});
function ajaxcall(callback){
  return $.ajax({
      url: "https://jsonplaceholder.typicode.com/users/1",
      type: "GET",
      dataType: 'json'
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2。将回调函数作为 ajaxCall

的参数传递

$(document).ready(function() {
  var response = ajaxcall((response)=>{
   console.log(response);
  }); 

});
function ajaxcall(callback){
 $.ajax({
    url: "https://jsonplaceholder.typicode.com/users/1",
    type: "GET",
    dataType: 'json',
    success: function(data){
        callback(data)
    }

  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

3.Use承诺

$(document).ready(function() {
  var response = ajaxcall().then(response=>{
     console.log(response)
  })

});
function ajaxcall(callback){
  return new Promise((resolve, reject) => {
   $.ajax({
          url: "https://jsonplaceholder.typicode.com/users/1",
          type: "GET",
          dataType: 'json',
          success: function(data){
              // success
              resolve(data)
          },
          error: function(e){
             reject(e)
          }

      });

  })
   

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

注意:在上面的示例中,我稍微修改了您的示例查询以使其在片段代码中起作用。

所以在你的情况下你必须 re-add 你的 headers 参数

url: "url",
type: "POST",
data: form_data,
dataType: 'json',
contentType: false,
cache: false,
processData:false,