2017-03-09 91 views
-1

我的主頁上有一個簡單的表單,表示POST是隨機生成的URL的輸入(由$random創建),然後在新選項卡中打開它。這種隨機URL運行腳本run.php無法使用PHP訪問AJAX數據

<form action="/run.php" method="POST" target="_blank"> 
    <input type="hidden" id="idgen" name="idgen" value="<?php echo $random ?>"> 
    <input type="text" name="userinput" id="userinput"> 
    <button type="submit" onclick="calcResult();">Go!</button> 
</form> 

我也有使用該userinput數據計算結果的網頁JavaScript函數。這個結果是(應該是)POST'發送到表單發送到的相同的隨機生成的網址。

function calcResult() { 
    var userinput = document.getElementById('userinput').value; 
    var randomid = document.getElementById('idgen').value; 

    // various functions 

    $.ajax({ 
      type: "POST", 
      url: 'http://example.com/' + randomid, // same random url 
      data: {result: "Hello"} 
    }); 

我再加入<?php echo $_POST['result']; ?>run.php文件

如果我打開Chrome開發工具的「網絡」選項卡(XHR)並提交表單(窗體打開運行run.php隨機URL) ,那麼這個AJAX POST does似乎工作(它發送到與表單相同的隨機鏈接。該隨機url的'響應'選項卡顯示run.php源代碼,甚至用AJAX結果"Hello"替換<?php echo $_POST['result']; ?>

因此,它在開發人員工具中成功工作,但它在實際的隨機url網頁("Hello"沒有顯示在實際網頁中,不像在開發人員工具中)工作。

我現在完全失去了什麼可能阻止我訪問網頁中的AJAX結果。

+2

'

'將數據發送到'run.php',而JavaScript函數正在對'隨機文件可能不存在的所有文件進行AJAX調用。你究竟想達到什麼目的? – tyteen4a03

+0

當你提交一個表單時,瀏覽器打開'action'屬性指定的頁面 - 在這種情況發生之前post請求不會完成 - 事實上,它可能永遠不會啓動 –

+0

@ tyteen4a03表單將數據發送到'run。然後(使用htaccess規則和PHP代碼)發送到一個隨機的url example.com/run.php ---> example.com/abcxyz(即運行run.php腳本)'AJAX調用我試圖訪問與表單數據相同的隨機網址上的AJAX數據 – Pebble

回答

0

我認爲沒有任何東西出來,因爲沒有回調函數,你可能只是重新加載頁面。我想你應該這樣做:

function calcResult(e) { 
    e.preventDefault(); 

    var userinput = document.getElementById('userinput').value; 
    var randomid = document.getElementById('idgen').value; 

    // various functions 

    $.ajax({ 
     type: "POST", 
     url: 'http://example.com/' + randomid, // same random url 
     data: {result: "Hello"}, 
     success: function(response){ 
     // callback - do what you wanna do 
     alert(response); 
     }, 
    }); 
} 

更新 -

考慮到要更改的頁面,並在run.php同時使用userinput和randomid,你可以在JS做到這一點:

function calcResult(e) { 
    e.preventDefault(); 

    var userinput = document.getElementById('userinput').value; 
    var randomid = document.getElementById('idgen').value; 

    // various functions 

    window.location.href = "http://example.com/run.php?randomid=" + randomid + "userinput=" + userinput; 

} 

然後,在run.php:

<?php 

    if(isset($_GET) { 

    $randomid = $_GET['randomid']; 
    $userinput = $_GET['userinput']; 

    // do what you want with both variables and return $result 

    echo $result; 

    } 

?> 

爲你的作品?

+0

我原本有一個回調函數(它也沒有工作),並且讀取它是可選的,所以刪除它。 – Pebble

+0

但是你想在這裏完成什麼 - 你想在一個div中顯示響應,例如? –

+0

是的,目的是在表單打開的隨機網址上顯示AJAX結果。 – Pebble