【问题标题】:Ajax.stop function with json request issue带有 json 请求问题的 Ajax.stop 函数
【发布时间】:2014-07-17 11:32:17
【问题描述】:

我试图从数据库中读取一些数据,但不等待页面加载,所以我创建了一个 ajax 帖子,当页面准备好时开始发送数据,现在在 ajax 完成后,我需要从另一个文件中读取值.问题是ajax完成后,正在读取数据的json运行不定。

JQUERY

<?php $url = $_GET['url']; ?>
var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0(document).ready(function () {
    var domain = '<?php echo $url; ?>';
    $.ajax({
        type: 'POST',
        url: 'lib/ajax.php',
        data: {
            action: 'get_all_seo_details', // function that collects data
            domain: domain // the domain that is being send to the function in order to get data
        },
        success: function (data) {
        // doesn't need to echo anything only to insert the data, which it done properly
        }
    });
  // Below is the second part of the script that starts when ajax stops
    $(document).ajaxStop(function () {
        $.getJSON('lib/get-details.php', function(data) {
            var twitter_followers = data.twitter_followers;
            $('#twitter-followers').html(twitter_followers);
        });
 // data is being read correctly but it loops repeatedly in the console without finishing
    });
});

PHP - get-details.php,用ajax插入后从数据库中读取数据

if (!isset($_SESSION)) {
    sec_start();
}
global $db;
$domain = isset($_SESSION['domain']) ? $_SESSION['domain'] : '';
if ($domain == '') {
    $domain = $db->query("SELECT * FROM seo_data");
} else {
    $domain = $db->query("SELECT * FROM seo_data WHERE domain = '$domain'");
}
$domain_now = $domain->fetch_assoc();
$twitter_followers = (int) $domain_now['twitter_followers'];
echo json_encode(array('twitter_followers' => $twitter_followers));

【问题讨论】:

    标签: javascript php jquery ajax json


    【解决方案1】:

    我不确定,但第一个 AJAX 请求何时停止

    $(document).ajaxStop(function (){....
    

    开始一个新的
    $.getJSON('lib/get-details.php', function(data) { ...
    

    当第二个结束时,也许

    $(document).ajaxStop(function (){....
    

    再次调用,再次开始第二个请求,依此类推

    【讨论】:

    • 在控制台中,ajax post 请求完成后,getjson 会启动并重复启动,但只有 getjson,ajax post 不会。
    • 再次阅读我的回答。当 ajax 发布停止时,ajaxStop 会触发 getJSON。当第一个 getJSON 结束时,ajaxStop 会再次触发,因为 Ajax 请求刚刚结束。 ajaxStop 第二次触发 getJSON 等等。
    • 您应该将您的 getJSON 调用放在您的 post 请求的成功回调中。当 post 请求结束时,它会被调用一次
    • $(document).ajaxStop(function () { console.log("ajaxStop 被调用"); $.getJSON('lib/get-details.php', function(data) { var twitter_followers = data.twitter_followers; $('#twitter-followers').html(twitter_followers); }); });
    • 尝试像我之前的评论一样添加这个console.log,以了解是否重复调用ajaxStop
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多