获取Ajax更改字段的值

时间:2016-07-07 13:02:10

标签: javascript jquery ajax

我正在进行ajax调用,它看起来像这样:

$.ajax({
     url: "index.php?id=70&type=999",
     type: 'post',
     data: form  + '&sort=' + val,
     success: function(response)
          {
            $(".listing").load(location.href + " .listing");
            $(".count").load(location.href + " .count");
          },
          complete: function (response) {
               alert( $(".count").val());
          },
        error: function(xhr, ajaxOptions, thrownError){
             alert(xhr.status);
        }
 });

所以,你可以看到2个班级"列出"和"计数"正在改变,这很好。在我试图提醒"计数"的新值之后上课,但总是给我实际的。在警报之后,价值会发生变化。但是complete:是不是意味着呼叫是在success:功能之后进行的?为什么首先发出警报并在ajax调用之前给我一个旧值?

3 个答案:

答案 0 :(得分:1)

成功的警示价值:

$.ajax({
     url: "index.php?id=70&type=999",
     type: 'post',
     data: form  + '&sort=' + val,
     success: function(response)
     {
         $(".listing").load(location.href + " .listing");
         $(".count").load(location.href + " .count", function(){
             alert( $(".count").val());
         });
      },
      error: function(xhr, ajaxOptions, thrownError){
         alert(xhr.status);
      }
 });

答案 1 :(得分:1)

尝试更改您的代码:

$.ajax({
                    url: "index.php?id=70&type=999",
                    type: 'post',
                    data: form  + '&sort=' + val,
                    success: function(response)
                    {
                        $(".listing").load(location.href + " .listing");
                        $(".count").load(location.href + " .count", function(){
                              alert( $(".count").val());
                         });
                    },
                    complete: function (data) {

                    },
                    error: function(xhr, ajaxOptions, thrownError){
                        alert(xhr.status);
                    }
                });

答案 2 :(得分:1)

问题是因为{em>第一次 AJAX请求之后complete触发,而不是在您通过调用load()创建的第二个/第三个AJAX请求之后触发。如果您想知道在.count方法中进行回调所需的load()值:

$.ajax({
    url: "index.php?id=70&type=999",
    type: 'post',
    data: form + '&sort=' + val,
    success: function(response) {
        $(".listing").load(location.href + " .listing");
        $(".count").load(location.href + " .count", function() {
            // get the value here, after load() completes
            console.log($(".count").val());
        });
    },
    error: function(xhr, ajaxOptions, thrownError){
        alert(xhr.status);
    }
});

另请注意,您可以通过仅调用load()次调用中的URL一次,然后从响应中提取所需信息来改进代码,如下所示:

$.ajax({
    url: "index.php?id=70&type=999",
    type: 'post',
    data: form + '&sort=' + val,
    success: function(response) {
        $.ajax({
            url: location.href,
            success: function(html) {
                $(".listing").html($(html).find('.listing'));
                $(".count").html($(html).find('.count'));
            }
        });
    },
    error: function(xhr, ajaxOptions, thrownError){
        alert(xhr.status);
    }
});