第一次函数是return Undefined,每隔一次它就工作一次?使用Jquery、Javascript、Ajax

First time function is return Undefined, every other time it works? Uses Jquery, Javascript, Ajax

本文关键字:一次 使用 工作 Jquery 函数 Ajax Javascript Undefined 第一次 return      更新时间:2023-09-26

第一次函数是return Undefined,每隔一次它工作并返回object。。。。

基本上,第一次存储var _d时,它是一个未定义的值。

它第一次存储值click是"未定义的",每隔一次都存储相应的值。

// jscript.js
function getDataById(This,table,Url)
{
    var Id = table.row(This.parent().parent()).data().id;
    $.ajax({
        url: Url + "/" + Id,
        type: "GET",
        dataType: 'json',
        success: function (Data) {
            var _d = Data;
            return _d;
        },
        error: function () {
            sweetAlert("Oops...", "Something went wrong!", "error");
        }
    });
    
}
/***********************/
$(document).ready(function () {
    $("#test tbody").on('click', '#aff', function () {
        console.log(  getDataById($(this),table,"test/email") );
    });
)};
/*****************/
// undefined

$.ajax()是异步的,success只是一个回调。函数getDataById必须有一个回调,该回调将在ajax请求之后调用

// jscript.js
function getDataById(This, table, Url, callback) {
  var Id = table.row(This.parent().parent()).data().id;
  $.ajax({
    url: Url + "/" + Id,
    type: "GET",
    dataType: 'json',
    success: function (Data) {
      callback(Data);
    },
    error: function () {
      sweetAlert("Oops...", "Something went wrong!", "error");
    }
  });
}
/***********************/
$(document).ready(function () {
    $("#test tbody").on('click', '#aff', function () {
      getDataById($(this), table, "test/email", function (data) {
        console.log(data);
      });
    });
  )
};
/*****************/