2016-04-20 44 views
0

我有一個PHP的大表格,有幾個表格,每個表格計算一個總和(價格和數量),然後有一個在最後計算總數。
的結構,或多或少,這樣的:重新提交表單以提交後錨定

<form action="" id="purchase_form"> 
    <div id="purchase_1"> 
     <table> 
      <input id="price_1"> 
      <input id="quantity_1"> 

      <input type="submit" name="calculate" value="Click here to calculate the partial"> 
     </table> 
    </div> 
    <div id="purchase_2"> 
     <table> 
      <input id="price_2"> 
      <input id="quantity_2"> 

      <input type="submit" name="calculate" value="Click here to calculate the partial"> 
     </table> 
    </div> 

    <tr> 
     <td id="price_sum"><?php *script* ?></td> 
     <td id="quantity_sum"><?php *script* ?></td> 
    </tr> 
</form> 

現在,當我點擊提交計算「部分」,它給我的總的,在同一時間。我知道這不是最新的形式,但無論如何,只是試圖對此視而不見。

我想要的是,當我點擊提交按鈕時,讓頁面重新載入顯示我點擊的窗體。就像,如果我點擊#purchase_1表格的提交,我希望頁面重新加載在#purchase_1表格中,依此類推。

是否有可能通過javascript來做到這一點?

回答

0

如果我很瞭解你,那是不可能的。您可以在客戶端進行計算,只要它們不復雜。如果你在後臺執行一些魔術,並且你不能在客戶端計算價格,你可以在表單提交一個xhr請求(注意:表單不會像往常那樣提交,所以頁面贏了不會被重新加載)。

如果您選擇第二個選項,完美解決方案將只檢索所需的一段html。不過,這不是強制性的。您可以在兩種情況下使用以下代碼:

var form = document.getElementById("purchase_form"); 
form.addEventListener("submit", function(e) { 
    e.preventDefault(); // we prevent the default action, which is a submit for the form element 

    var xhr = new XMLHttpRequest(); // create a new XHR object. 
    xhr.open("GET", form.action, true); // open the async connection 
    xhr.addEventListener("load", function() { 
    var doc = document.implementation.createHTMLDocument(""); // you could use DOMParser aswell, but parsing html via DOMParser is not supported in in Safari < 7.1 and IE < 10. 
    doc.documentElement.insertAdjacentHTML("afterbegin", xhr.response); 

    // now you would have to retrieve the element where the partial price is displayed and insert that value to desired element. 
    // you can do it like document.querySelector(desiredElement).textContent = doc.querySelector(selectorToElementToGetValueFrom).textContent 

    }); 
    xhr.addEventListener("error", function() { 
    // error happened... you can handle the action for exception here 
    }); 
    xhr.send(new FormData(form)); 
}); 

如果您有任何其他問題,請隨時向我提問。