jQuery Ajax调用-设置成功的变量值[复制]

时间:2021-12-22 20:04:54

This question already has an answer here:

这个问题已经有了答案:

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.

我有一个正在编写的应用程序,用于修改服务器中缓存对象上的数据。修改是通过ajax调用执行的,该调用基本上更新了该对象的属性。当用户完成工作后,我有一个基本的“保存更改”按钮,允许用户保存数据并刷新缓存的对象。

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.

为了保护用户,我想警告他们,如果在对服务器对象进行修改时,如果它们没有保存,则尝试从页面中导航。因此,我创建了一个名为IsInitialized的web服务方法,它将根据是否保存更改返回true或false。如果没有保存,我想提示用户并给他们取消导航请求的机会。

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.

这是我的问题——尽管调用工作正常,但我似乎无法获得ajax成功调用来设置回调函数的变量值。这是我现在的代码。

   ////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?

我觉得我可能试图用不恰当的方式使用成功回调。如何在成功回调上设置一个javascript变量,以便决定是否应该提示用户w/未保存的更改消息?

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)

正如刚才指出的,我正在进行一个异步调用,这意味着在方法返回之前调用其余的代码。是否有一种方法可以使用ajax调用,但仍然可以捕获窗口。onunload事件吗?(无需synchronos ajax)

7 个解决方案

#1


32  

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.

向JSON中添加async: false进行同步调用。

#2


7  

An example of jquery page:

jquery页面示例:

var html = $.ajax({
  url: "some.php",
  async: false
 }).responseText;

Source: http://api.jquery.com/jQuery.ajax/

来源:http://api.jquery.com/jQuery.ajax/

#3


4  

The thing is that the request to Ajax call is asynchronous. So by the time you are checking you IsInitialized the call has not finished yet.

问题是对Ajax调用的请求是异步的。所以当你检查你已经初始化的时候调用还没有结束。

I suggest specifying your behaviour in the success function.

我建议在success函数中指定您的行为。

Basically having synchronous calls with ajax is if not impossible than really discouraged.

基本上,使用ajax进行同步调用是不可能的,但实际上是不鼓励的。

#4


2  

You could theoretically kill the event (return false) and close the window on success, but I think you would run into Javascript restrictions set by some users, and also just confuse them as to why their window isn't closing. So, I agree with Pawel Krakowiak, the ajax call itself must be synchronous.

理论上,您可以终止事件(返回false)并关闭成功窗口,但我认为您可能会遇到一些用户设置的Javascript限制,并将它们混淆为为什么窗口没有关闭。因此,我同意Pawel Krakowiak的观点,ajax调用本身必须是同步的。

I'll add that you'll want to give the user some notification that you are checking on status (not a popup, please. one of those nice notification banners at the top of the window) and be sure to set the $.ajax "timeout" option to something more reasonable for this situation, so they aren't waiting forever for the window to close.

我将添加,您将希望给用户一些您正在检查状态的通知(请不要弹出窗口)。在窗口顶部有一个很好的通知横幅)并且一定要设置$。ajax“timeout”选项用于更合理的情况,因此它们不会永远等待窗口关闭。

#5


2  

I had a similar problem with attempting to set a property for a data object through the success callback of an ajax request. Using async: false didn't solve my issue, either. What I ended up doing was to use a setTimeout call outside the ajax call, and set the timeout value to 1, like so:

我在尝试通过ajax请求的成功回调来为数据对象设置属性时遇到了类似的问题。使用async: false也不能解决我的问题。我最后做的是在ajax调用之外使用setTimeout调用,并将超时值设置为1,如下所示:

function getSessionid() {  
    $.ajax({  
        type: 'POST',  
        url: 'getSession.php',  
        dataType: 'text',  
        success: function(result){myData.sessionid = result;},   
        error: function(data) {alert("Error!\n" + data);} 
    });  
    setTimeout(function() {alert('sessionid = ' + myData.sessionid);},1);  
}  

Just having that 1 millisecond delay made all the difference in the world. Without it, the sessionid property wouldn't set outside the ajax call, though alerts within the callback showed that it was, indeed, being set. It's something to think about, should you come up against a similar problem.

仅仅有1毫秒的延迟就能改变世界。如果没有它,sessionid属性将不会在ajax调用之外设置,不过回调中的警报显示它确实正在设置。

#6


1  

Looks like the best approach for me was to use the async: false option on my ajax call. Although I understand Rashack's hesitation for doing this, I think that this situation justifies the means.

看起来对我来说最好的方法是在ajax调用中使用async: false选项。虽然我理解拉沙克的犹豫,但我认为这种情况证明了方法的合理性。

Also great point by Jerph about making sure that I don't leave the user hanging while I am trying to verify their status. That coupled w/ the timeout option is important.

Jerph还提出了一个很好的观点,就是确保我在验证用户的状态时不会让用户挂着。耦合的w/ timeout选项很重要。

Thanks to everyone who commented.

谢谢大家的评论。

#7


0  

see here:

在这里看到的:

http://groups.google.com/group/jquery-dev/browse_thread/thread/40d0e3def47148a0

http://groups.google.com/group/jquery-dev/browse_thread/thread/40d0e3def47148a0

#1


32  

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.

向JSON中添加async: false进行同步调用。

#2


7  

An example of jquery page:

jquery页面示例:

var html = $.ajax({
  url: "some.php",
  async: false
 }).responseText;

Source: http://api.jquery.com/jQuery.ajax/

来源:http://api.jquery.com/jQuery.ajax/

#3


4  

The thing is that the request to Ajax call is asynchronous. So by the time you are checking you IsInitialized the call has not finished yet.

问题是对Ajax调用的请求是异步的。所以当你检查你已经初始化的时候调用还没有结束。

I suggest specifying your behaviour in the success function.

我建议在success函数中指定您的行为。

Basically having synchronous calls with ajax is if not impossible than really discouraged.

基本上,使用ajax进行同步调用是不可能的,但实际上是不鼓励的。

#4


2  

You could theoretically kill the event (return false) and close the window on success, but I think you would run into Javascript restrictions set by some users, and also just confuse them as to why their window isn't closing. So, I agree with Pawel Krakowiak, the ajax call itself must be synchronous.

理论上,您可以终止事件(返回false)并关闭成功窗口,但我认为您可能会遇到一些用户设置的Javascript限制,并将它们混淆为为什么窗口没有关闭。因此,我同意Pawel Krakowiak的观点,ajax调用本身必须是同步的。

I'll add that you'll want to give the user some notification that you are checking on status (not a popup, please. one of those nice notification banners at the top of the window) and be sure to set the $.ajax "timeout" option to something more reasonable for this situation, so they aren't waiting forever for the window to close.

我将添加,您将希望给用户一些您正在检查状态的通知(请不要弹出窗口)。在窗口顶部有一个很好的通知横幅)并且一定要设置$。ajax“timeout”选项用于更合理的情况,因此它们不会永远等待窗口关闭。

#5


2  

I had a similar problem with attempting to set a property for a data object through the success callback of an ajax request. Using async: false didn't solve my issue, either. What I ended up doing was to use a setTimeout call outside the ajax call, and set the timeout value to 1, like so:

我在尝试通过ajax请求的成功回调来为数据对象设置属性时遇到了类似的问题。使用async: false也不能解决我的问题。我最后做的是在ajax调用之外使用setTimeout调用,并将超时值设置为1,如下所示:

function getSessionid() {  
    $.ajax({  
        type: 'POST',  
        url: 'getSession.php',  
        dataType: 'text',  
        success: function(result){myData.sessionid = result;},   
        error: function(data) {alert("Error!\n" + data);} 
    });  
    setTimeout(function() {alert('sessionid = ' + myData.sessionid);},1);  
}  

Just having that 1 millisecond delay made all the difference in the world. Without it, the sessionid property wouldn't set outside the ajax call, though alerts within the callback showed that it was, indeed, being set. It's something to think about, should you come up against a similar problem.

仅仅有1毫秒的延迟就能改变世界。如果没有它,sessionid属性将不会在ajax调用之外设置,不过回调中的警报显示它确实正在设置。

#6


1  

Looks like the best approach for me was to use the async: false option on my ajax call. Although I understand Rashack's hesitation for doing this, I think that this situation justifies the means.

看起来对我来说最好的方法是在ajax调用中使用async: false选项。虽然我理解拉沙克的犹豫,但我认为这种情况证明了方法的合理性。

Also great point by Jerph about making sure that I don't leave the user hanging while I am trying to verify their status. That coupled w/ the timeout option is important.

Jerph还提出了一个很好的观点,就是确保我在验证用户的状态时不会让用户挂着。耦合的w/ timeout选项很重要。

Thanks to everyone who commented.

谢谢大家的评论。

#7


0  

see here:

在这里看到的:

http://groups.google.com/group/jquery-dev/browse_thread/thread/40d0e3def47148a0

http://groups.google.com/group/jquery-dev/browse_thread/thread/40d0e3def47148a0