2017-01-23 157 views
0

我有(工作):第一頁 - 用戶輸入字符串並按提交按鈕。此參數通過會話發送到運行某種腳本命令並顯示結果(輸出)的其他頁面。這裏的代碼,使之更加明確:php javascript刷新頁面

第一頁:

<?php 
    session_start(); 
    echo "<input type=\"text\" id=\"userInput\">"; 
    echo "<br><button onclick=\"submit()\">Submit</button>"; 
    $_SESSION[''] = $input; 
?> 

<script type="text/javascript"> 
    var submit = function() { 
     input = document.getElementById("userInput").value; 
     window.open ('secondPage.php?userInput=' + input,'_self',false);} 
</script> 

第二頁:

<?php 
    session_start(); 
    $input = $_GET['userInput']; 
    $command = "./myScript.py $input"; 
    system($command, $retval); 
?> 

現在,我想有兩個在一個單一頁面,即當頁面打開時,輸入字段和按鈕將位於頂部,在它下面將是第二頁命令的輸出,每當用戶「提交」另一個輸入時(第一次userInput將爲空),刷新該輸入字段和按鈕。希望很明顯,或多或少。任何幫助?

+0

那麼你爲什麼不嘗試和代碼的東西做 – RiggsFolly

+0

似乎會有小點提交頁面,你可以做一切與一些JavaScript並沒有頁面提交 – RiggsFolly

+0

你可能會更具體嗎? – user1418018

回答

1

我想這是你所需要的:

<?php 
    session_start(); 

    // We check if there's POST data 'userInput' 
    if (isset($_POST['userInput'])) { 
     // 'userIput' exists, we make our process and return what we need. 
     echo 'User inputed '.$_POST['userInput']."<br>"; 
    } else { 
     // 'userIput' does not exists, displaying page content. 
     ?> 
     <input id="userInput" type="text" /><button id="btn">Send</button> 
     <div id="result"> 
      <!-- Displaying AJAX results here --> 
     </div> 
     <script type="text/javascript"> 

      // Send an XMLHttpRequest 
      function sendRequest(url, postData, callback) { 
       var req = new XMLHttpRequest(); 
       if (!req) 
        return; 
       var method = (postData) ? "POST" : "GET"; 
       req.open(method,url,true); 
       if (postData) 
        req.setRequestHeader('Content-type','application/x-www-form-urlencoded'); 
       req.onreadystatechange = function() { 
        if (req.readyState != 4) 
         return; 
        if (req.status != 200 && req.status != 304) { 
         return; 
        } 
        callback(req); 
       } 
       if (req.readyState == 4) 
        return; 
       req.send(postData); 
      } 

      // We bind the 'click' event on the button 
      document.getElementById("btn").addEventListener('click', function(e) { 
       var input = document.getElementById("userInput").value; 
       // Use AJAX 
       sendRequest("#", 'userInput='+input, function(data) { 
        // Data returned, inserting in our 'result' div. 
        var resDiv = document.getElementById("result"); 
        resDiv.innerHTML = resDiv.innerHTML + data.responseText; 
       }); 
      }); 
     </script> 

     <?php 
    } 
+0

謝謝麥克託塔託爵士,這非常有幫助。 – user1418018

+0

不客氣!你應該明確地看看jQuery,它爲你的DOM元素,事件監聽器提供了一個很好的訪問接口,並且還簡化了一個LOT ajax查詢;) –