1

我正在尝试使用 ajax 进行一些验证。它从我的 MVC3 控制器调用一个方法,但无论控制器返回 true 还是 false,它都返回 true。始终显示警报。

ClientChoices/HasJobInProgress

 public Boolean HasJobInProgress(int clientId)
        {
            return false;
            //return _proxy.GetJobInProgress(clientId);
        }

jQuery.Ajax

 $("#saveButton").click(function() {
        var hasCurrentJob =  
            $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: @Model.ClientId },
            success: function(data){
                return data;
            }
            });
        if (hasCurrentJob) {
            alert("The current clients has a job in progress. No changes can be saved until current job completes");
        } 
    });

解决方案

$("#saveButton").click(function() {
            $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function(data){
                showMsg(data);
            },
            cache: false
        });
    });

    function showMsg(hasCurrentJob) {
          if (hasCurrentJob.toString()=="True") {
               alert("The current clients has a job in progress. No changes can be saved until current job completes");
          } 
    }
4

1 回答 1

3

AJAX 调用是异步的,您的返回数据不会设置值,hasCurrentJob它是对成功回调的返回。请参阅下文,了解如何基于data.

    $("#saveButton").click(function() {
        //var hasCurrentJob
            $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: @Model.ClientId },
            success: function(data){
                showMsg(data);
            }
            });

    });

    function showMsg(hasCurrentJob) {
          if (hasCurrentJob === 'true') {
               alert("The current clients has a job in progress. No changes can be saved until current job completes");
          } 
    }
于 2012-04-10T14:20:59.933 回答