2017-07-25 81 views
1

我正在嘗試加載B.phpa.php只會在功能執行後,並從通過使用交陣列一些數據a.php只會乙.php在同一時間內。通過數據

代碼列表如下 a.php只會

<script type="text/javascript"> 
    alert_for_the_fucntion(); 
    window.location.href = "B.php"; 
    function alert_for_the_fucntion() { 
      $.post("B.php", {action: 'test'}); 
    } 
</script> 

B.php

<?php 
if (array_key_exists("action", $_POST)) { 
    if ($_POST['action'] == 'test') { 
     echo 'ok';  
    }  
}  
?> 

用於測試目的,我想呼應的B.php東西。但目前這是行不通的。我犯過什麼錯誤嗎?或者是否有任何可能的方法來做到這一點。

+1

什麼是'B.php.php'? –

+0

有一個錯字應該是'window.location.href =「B.php」;'而不是'window.location.href =「B.php.php」;'爲什麼要重定向? – funilrys

+1

問題是關於window.location.href,這會讓你在進行ajax調用之前更改頁面。 – Salketer

回答

3

您的代碼做到這一點:

  1. 告訴瀏覽器導航到B.php(使用GET請求)
  2. 使用XMLHttpRequest的

POST請求可能觸發一個POST請求因瀏覽器立即離開頁面而被取消(並且XHR請求是異步的)。如果沒有,那麼響應將被忽略。無論哪種方式,它都沒有效果。

然後您會看到瀏覽器窗口中顯示的GET請求(顯然,不包括$_POST['action'])的結果。


如果你想以編程方式生成一個POST請求和結果顯示爲一個新的頁面,那麼你需要提交表單

請勿使用location。請勿使用XMLHttpRequest(或任何環繞它的東西,例如$.ajax)。

var f = document.createElement("form"); 
f.method = "POST"; 
f.action = "B.php"; 

var i = document.createElement("input"); 
i.type = "hidden"; 
i.name = "action"; 
i.value = "test"; 

f.appendChild(i); 
document.body.appendChild(f); 
f.submit(); 

如果要處理JavaScript中的結果的話:

  1. 不要導航到不同的頁面(使用`位置刪除線)
  2. 添加done處理器到阿賈克斯代碼

eg

$.post("B.php", {action: 'test'}).done(process_response); 

function process_response(data) { 
    document.body.appendChild(
     document.createTextNode(data) 
    ); 
} 
+0

嗨,先生,謝謝你的好主意 我已經嘗試過這種方式,但仍然沒有工作 document.getElementById('jsform' )。提交(); <表格ID = 「jsform」 行動= 「B.php」 方法= 「POST」 目標= 「_空白」>

1

試試這個:

的Javascript:

<script type="text/javascript"> 
    window.onload = alert_for_the_fucntion; 
    function alert_for_the_fucntion() { 
     $.post("B.php", 
       { 
       action: 'test' 
       }, 
       function(data, status){ 
        if(status=="success"){ 
        alert(data); 
        } 
       } 
     ); 
    } 
</script> 

PHP

<?php 
if(isset($_POST['action'])){ 
     echo $_POST['action'];  
} 
?>