jQuery Ajax call - Set variable value on success [

2020-06-06 08:15发布

I have an application that I am writing that modifies data on a cached object in the server. The modifications are performed through an ajax call that basically updates properties of that object. When the user is done working, I have a basic 'Save Changes' button that allows them to Save the data and flush the cached object.

In order to protect the user, I want to warn them if the try to navigate away from the page when modifications have been made to the server object if they have not saved. So, I created a web service method called IsInitialized that will return true or false based on whether or not changes have been saved. If they have not been saved, I want to prompt the user and give them a chance to cancel their navigation request.

Here's my problem - although I have the calls working correctly, I can't seem to get the ajax success call to set the variable value on its callback function. Here's the code I have now.

   ////Catches the users to keep them from navigation off the page w/o saved changes...
window.onbeforeunload = CheckSaveStatus;
var IsInitialized;

function CheckSaveStatus() {

    var temp = $.ajax({
        type: "POST",
        url: "URL.asmx/CheckIfInstanceIsInitilized",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            IsInitialized = result.d;
        },
        error: function(xmlHttpRequest, status, err) {
            alert(xmlHttpRequest.statusText + " " + xmlHttpRequest.status + " : " + xmlHttpRequest.responseText);
        }

    });

    if (IsInitialized) {
        return "You currently have unprocessed changes for this Simulation.";
    }
}

I feel that I might be trying to use the Success callback in an inappropriate manner. How do I set a javascript variable on the Success callback so that I can decide whether or not the user should be prompted w/ the unsaved changes message?

As was just pointed out, I am making an asynchronous call, which means the rest of the code gets called before my method returns. Is there a way to use that ajax call, but still catch the window.onunload event? (without making synchronos ajax)

7条回答
孤傲高冷的网名
2楼-- · 2020-06-06 08:58

Since you need this behavior in the unload event, you will have to make a synchronous call instead. However it may freeze the browser window/tab dependent on how long the call will take, but because you're effectively trying to prevent the user from closing the window...

Add async: false to your JSON to make a synchronous call.

查看更多
登录 后发表回答