簡體   English   中英

jQuery Ajax等待獲取頁面

[英]Jquery ajax wait before fetching page

地獄人...讓一個簡單的Ajax代碼...

    $.ajax({
      method: "POST",
      url: "some.php",
      data: { name: "John", location: "Boston" }
    })
      .done(function( msg ) {
        alert(msg.html());
      });

我正在等待5秒后嘗試獲取msg.html() 所以過程如下...

  1. 發送數據到some.php
  2. 等待5秒鍾
  3. 然后返回html頁面數據。

我們怎樣才能做到這一點?

使用setTimeout ,setTimeout()方法將在指定的毫秒數后調用一個函數或計算一個表達式。 該功能僅執行一次。

如果要獲取msghtml ,則首先要確保msg是有效的HTML字符串,並且在獲取.html()之前,請先通過$(msg)將其轉換為jQuery對象。

$.ajax({
    method: "POST",
    url: "some.php",
    data: {
      name: "John",
      location: "Boston"
    }
  })
  .done(function(msg) {

    setTimeout(function() {
      alert($(msg).html());
    }, 5 * 1000);

  });
$.ajax({
      type : 'POST',
      url  : 'some.php',
      data :{ name : 'John', location : 'Boston'},
      beforeSend : function(){
        //you can do whatever you want here (loading gif etc.) until some.php responds 
      },
      complete : fuction(){
    //Here is for after responding
      },
      success : function(data){
      //data is the response of some.php, you can use the data to fill some elements in DOM etc.
    }


    });

    setTimeout(function(){
    //the codes you write here fires after 5 secs
    },5000);

您可以將其傳遞給您想要的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM