2016-04-20 49 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)); 
}); 

如果您有任何其他问题,请随时向我提问。