2015-03-13 72 views
0

我已經搜索並找不到答案。我有一個循環並等待變量的ajax,當它不等於0時,我想將數據發送到另一個腳本,以便它可以更新數據庫,然後重定向到另一個URL。我試過.post和.get,並且無法獲取值來更新數據庫,但腳本確實重定向。在ajax成功觸發php腳本

function updateTrigger(){ 
      $.ajax({ 
       url: "json.trigger.php", 
       dataType: "json", 
       cache: false, 
       success: function(data) { 
        var scrape_type = data.scrape_type; 
        var account_id = data.account_id; 
         if(account_id != 0) { 
          $.post('update-pending.php', {account_id: account_id, scrape_type: scrape_type}); 
          document.location.href="redirect.com"; 
          } 
       }    
      });    
     } 

這是我的update-pending.php,我將變量發送到第一個重定向之前。

$account_id = $_POST['account_id']; 
$scrape_type = $_POST['scrape_type']; 

$stmt = $con->prepare("UPDATE triggers SET 
      pending='1' 
      WHERE account_id = '$account_id' AND scrape_type = '$scrape_type'") or die(mysql_error()); 
$stmt->execute(); 
+2

**危險**:您很容易[SQL注入攻擊](http://bobby-tables.com/)**,您需要[防守](http://stackoverflow.com/問題/ 60174/best-way-to-prevent-sql -injection-in-php)自己從。 – Quentin 2015-03-13 18:48:17

+0

我會嘗試設置'document.location。href ='分配給'$ .post'函數的回調函數。也許重定向正在處理'$ .post'可以做任何事情之前。 – 2015-03-13 18:51:02

+0

即使我註釋掉重定向我仍然無法獲取數據庫更新 – 2015-03-13 18:55:38

回答

1

您在運行觸發POST請求的JS後立即離開頁面。這會導致POST請求被取消。

在將location設置爲新值之前,您需要等到收到POST請求的響應。

+0

我想測試這個,但我很確定POST實際上會在頁面位置發生變化之前啓動,問題是發佈響應的事件處理程序將被清除,因此您將永遠不會看看它說什麼。我懷疑實際的錯誤出現在最初的ajax調用中,這可能會爲POST生成不良的json數據。 – 2015-03-13 19:08:00

+0

如果我提醒每個變量的數據我得到正確的變量 – 2015-03-13 19:17:08

+0

Ajax中的A代表異步。必須在這裏同意昆汀。乍得,'提醒'或'確認'或'提示'會導致頁面等待,直到您關閉模式。所以這就是爲什麼它適用於警報。否則它是異步的。 – skidadon 2015-03-13 19:30:35

1

重要提示:檢查答案的最後部分,您需要更改您的PHP代碼以避免SQL注入。

您正在爲POST請求生成相應的承諾,但它永遠不會執行,因爲您在此之前離開頁面。

簡單的調用.done方法以回調作爲您的$ .post()承諾的參數,該回調將在帖子成功後執行,還可以考慮添加.fail()它將要執行的如果帖子失敗,將被執行。

$.post('update-pending.php', { 
    account_id: account_id, 
    scrape_type: scrape_type 
}).done(function() { 
    document.location.href="redirect.com"; 
}).fail(function() { 
//enter code here 
}; 

在服務器中,您需要在過程結束時返回對發佈請求的響應。如果沒有,$ .post將會返回錯誤並且總是執行.fail()。

如果您不能/不想等待php腳本完成其執行以將用戶重定向到redirect.com,請考慮在服務器的後臺執行輔助腳本。

我更新了pending.php使用PDO:

//update-pending.php 
/* Consider executing this in the background, (adapted) */ 
$account_id = $_POST['account_id']; 
$scrape_type = $_POST['scrape_type']; 

$params = array('account_id' => $account_id, 'scrape_type' => $scrape_type); 

$query = "UPDATE triggers SET pending='1' 
      WHERE account_id = :account_id 
      AND scrape_type = :scrape_type"; 

$stmt = $con->prepare($query); 
$stmt->execute($params); 
/* End of background script */ 
return true; // Return a response to the POST request. 

沒有測試(現在不能),但你的想法。

0

1) 解決此問題的最簡單方法是使用內置的javascript函數settimeout()。但處理定時器是可怕的,因爲你不知道腳本什麼時候完成。

2) 解決此問題的最簡單方法是實現一個回調函數,該函數在第一個方法完成後觸發。其實,這並不難。

3) 另一種方式可能是實現某種形式的「jsonp」實現來處理和與您的PHP腳本進行交互。

如果這是一個快速入侵,只需要選擇1.如果沒有,玩2和3的組合。祝你好運的夥伴。