javascript - AJAX GET 在第一次调用时返回未定义,但在第二次调用时有效

标签 javascript php jquery asp.net ajax

我正在 ASP.NET MVC 中开发一个房地产 Web 应用程序。我的问题出在我的预订部分。 enter image description here

我正在使用 AJAX 在返回 JSONResult 的 Controller 中发布。这是我的代码:

Controller

[HttpPost]
public JsonResult SubmitReservation(ReservationViewModel rvm)
{
    return Json(rvm, JsonRequestBehavior.AllowGet);
}

主要 AJAX

    var rvm = new ReservationViewModel();

    getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
    getSiteInfo(rvm.SelectedSiteID, siteCallback);
    getUnitInfo(rvm.SelectedUnitID, unitCallback);

    $.ajax({
        url: "/Reservations/SubmitReservation",
        data: JSON.stringify(rvm),
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        success: function () {

            console.log(clientData);
            console.log(siteData);
            console.log(unitData);
            //Assignment of data to different output fields

            //Client Data
            $('#clientName').html(clientData.FullName);
            $('#clientAddress').html(clientData.Residence);
            $('#clientContact').html(clientData.ContactNumber);

            //Site Data
            $('#devSite').html(siteData.SiteName);
            $('#devLoc').html(siteData.Location);

            ////House Unit Data
            $('#unitBlock').html(unitData.Block);
            $('#unitLot').html(unitData.Lot);
            $('#modelName').html(unitData.ModelName);
            $('#modelType').html(unitData.TypeName);
            $('#lotArea').html(unitData.LotArea);
            $('#floorArea').html(unitData.FloorArea);
            $('#unitBedrooms').html(unitData.NumberOfBedrooms);
            $('#unitBathrooms').html(unitData.NumberOfBathrooms);
            $('#unitPrice').html(unitData.Price);

            $('#reservationDetails').show();
            alert("Success!");
        },
        error: function (err) {
            alert("Error: " + err);
        }
    });

获取数据的函数

function getBuyerInfo(id, cb) {
   $.ajax({
       url: "/BuyersInformation/GetBuyerByID/" + id,
       type: "GET",
       contentType: "application/json",
       dataType: "json",
       success: cb
  });
 }

function getSiteInfo(id, cb) {
    $.ajax({
        url: "/Sites/GetSiteByID/" + id,
        type: "GET",
        contentType: "application/json",
        dataType: "json",
        success: cb
     });
 }

function getUnitInfo(id, cb) {
    $.ajax({
        url: "/HouseUnits/GetUnitByID/" + id,
        type: "GET",
        contentType: "application/json",
        dataType: "json",
        success: cb
     });
  }

function ReservationViewModel() {

var buyerId = $('#SelectedBuyerID').val();
var siteId = $('#SelectedSiteID').val();
var unitId = $('#SelectedUnitID').val();
var rsvDate = $('#ReservationDate').val();

var me = this;
me.ReservationDate = rsvDate;
me.SelectedBuyerID = buyerId;
me.SelectedSiteID = siteId;
me.SelectedUnitID = unitId;

}

function clientCallback(result) {
    clientInfo = result;
    clientData = clientInfo[0];
 }

function siteCallback(result) {
   siteInfo = result;
   siteData = siteInfo[0];
 }

function unitCallback(result) {
    unitInfo = result;
    unitData = unitInfo[0];
}

整个代码第二次运行良好。然而,它第一次不起作用。当我刷新页面并点击“创建”时,它返回未定义。但是当我再次点击该按钮而不刷新页面时,它运行良好。有人可以向我解释一下这个吗?为什么 AJAX 最初返回 undefined 而在后续调用时不返回?提前致谢。

最佳答案

您正在代码中的这些函数内调用多个 ajax 请求:

getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);

最后是$.ajax({...}),您可以在其中使用之前的 ajax 调用的结果。

您的问题是,第一个 ajax 调用不一定会在启动最后一个 ajax 之前返回结果,因为它们都是异步的。在调用最后一个 ajax 之前,您必须确保收到三个响应。使用 Promise 或 jQuery when,如下所示:

var rvm = new ReservationViewModel();

$.when( 

    $.ajax({
       url: "/BuyersInformation/GetBuyerByID/" + rvm.SelectedBuyerID,
       type: "GET",
       contentType: "application/json",
       dataType: "json"
    }),

    $.ajax({
        url: "/Sites/GetSiteByID/" + rvm.SelectedSiteID,
        type: "GET",
        contentType: "application/json",
        dataType: "json"
     }),

    $.ajax({
        url: "/HouseUnits/GetUnitByID/" + rvm.SelectedUnitID,
        type: "GET",
        contentType: "application/json",
        dataType: "json"
     })

).done(function ( clientResponse, siteResponse, unitResponse ) {

    clientInfo = clientResponse;
    clientData = clientInfo[0];          

    siteInfo = siteResponse;
    siteData = siteInfo[0];

    unitInfo = unitResponse;
    unitData = unitInfo[0];          

    $.ajax({ ... }) // your last ajax call

});

关于javascript - AJAX GET 在第一次调用时返回未定义,但在第二次调用时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34984531/

相关文章:

php - php中包含文件的范围丢失

php - 文本搜索 - 突出显示搜索短语

jquery - 单击 img 占位符以上传图像而不是该占位符

jquery - 在 jQuery 中绑定(bind)事件的更好方法

javascript - jQuery 显示数组项给我 [object, Object]

javascript - 如果 ID 已在列表中,则不允许添加产品

javascript - charAt() 第二次无法在 javascript 函数中工作

php - 我想在存储日期 20 天后自动更新我的 sql 表数据

javascript - 如何获取 Angular 动态表单字段值?

javascript - 使用存储在数组中的 JS 颜色值来设置 P5.js Dom 元素的样式