服务器请求时Ajax响应错误

时间:2011-07-31 12:06:09

标签: jquery ajax

您好我有一个ajax代码如下:

$.ajax({
                type:"POST",
                url: 'sample.php',
                data:"data="+data,
                success: function(server_response) { 
                $('.functions').ajaxComplete(function(event, request){

                  if(server_response == 0)
                     {
                                showmsg('An email with instructions to reset password has been sent to your email address. Please check it.');
                     }
                  else if(server_response == 1)
                    {
                                showmsg('Email address was not found in our database. Please enter a valid email address');
                    }
                  else
                    {
                                showmsg('Some problem occured while sending you an email. Please try again.');                                    
                    }


                                exit();
        });

代码第一次正常工作。但是,如果我提交没有页面刷新的代码,则会收到先前的响应。就像我第一次加载页面一样,我从sample.php得到的响应为0,消息显示正确。但是,如果我在没有页面刷新的情况下进行ajax调用,并且我将sample.php的响应作为1,则会显示上一条消息。无论我得到什么输出,我都会得到相同的信息,直到我刷新页面。有什么问题?代码工作正常。

2 个答案:

答案 0 :(得分:2)

您的回复正在被缓存,因此您需要阻止它。如果您使用jQuery,有三种广泛使用的解决方案。

设置jQuery (指示AJAX调用不缓存结果)

$(document).ready(function(){
    $.ajaxSetup({ 
        cache: false 
    });
});

随机数学种子(添加到网址会使服务器认为是新请求)

$.ajax({
    type:"POST",
    url: 'sample.php?rnd=' + Math.random(),
    data:"data="+data,
    success: function(server_response) { 
    //... rest of the code      
});

使用当前时间戳作为种子(与之前的时间戳相同,除了使用当前时间戳)

$.ajax({
    type:"POST",
    url: 'sample.php?rnd=' + Date().getTime(),
    data:"data="+data,
    success: function(server_response) { 
    //... rest of the code      
});

第一个选项很好,以防在单个页面上发出大量的ajax请求而没有实际的缺点。

第二种选择几乎总是一个不错的选择。它也没有特别的缺点。

第三个选项也很好但是在每秒发出多个AJAX请求的页面上可能会很危险,因为有时相同的时间戳可用于两个不同的请求,后续调用将接收缓存数据。

编辑:如果页面上没有$(document).ready(),则可以在结束</head>标记之前添加到主要部分。

<head>
    <!-- Whatever code already exists in the head section -->
    <script type="text/javascript">
        $(document).ready(function(){
            $.ajaxSetup({ 
                cache: false 
            });
        });
    </script>
</head>

答案 1 :(得分:1)

您是否确认在服务器端代码上实际接收并处理了后续请求?在这些情况下返回的服务器端代码是什么?也许那里存在问题?

仅基于此描述,听起来响应只是被缓存。 $.ajax()可以选择禁用缓存:cache: false。无论浏览器缓存如何,这都会强制jQuery代码每次都向服务器提交请求。

更多信息here