HTML:
<code><form id="info"> <label for="id">ID: </label> <input type="text" name="id"> <br> <label for="user">User: </label> <input type="text" name="user" id="user"> <br> <input type="submit" name="submit" id="submit"> </form></code>
JavaScript:
<code>var submit = document.getElementById("submit"); submit.onclick = function() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.state == 4) { if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { console.log(xhr.responseText); } else { alert("HttpRequest was unsccessful: " + xhr.status); } } } xhr.open("post", "form.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var form = document.getElementById("info"); xhr.send(serialize(form)); }</code>
form.php
<code><?php $id = $_POST['id']; $user = $_POST['user']; echo $id . $user; ?></code>
程式碼如上, 我想要達到的效果, 是跟在form裡添加了action和method屬性一樣, 提交後可以自動跳到form.pp.
但是這樣提交並沒有反應, 搜了一下, 全是關於jquery的. 還是不知道用ajax提交表單是怎樣的格式.
HTML:
<code><form id="info"> <label for="id">ID: </label> <input type="text" name="id"> <br> <label for="user">User: </label> <input type="text" name="user" id="user"> <br> <input type="submit" name="submit" id="submit"> </form></code>
JavaScript:
<code>var submit = document.getElementById("submit"); submit.onclick = function() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.state == 4) { if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { console.log(xhr.responseText); } else { alert("HttpRequest was unsccessful: " + xhr.status); } } } xhr.open("post", "form.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var form = document.getElementById("info"); xhr.send(serialize(form)); }</code>
form.php
<code><?php $id = $_POST['id']; $user = $_POST['user']; echo $id . $user; ?></code>
程式碼如上, 我想要達到的效果, 是跟在form裡添加了action和method屬性一樣, 提交後可以自動跳到form.pp.
但是這樣提交並沒有反應, 搜了一下, 全是關於jquery的. 還是不知道用ajax提交表單是怎樣的格式.
試試將xhr.send(serialize(form))
改為
<code>var formData = new FormData(form); xhr.send(formData);</code>
formData是HTML5用於非同步提交表單的,應該可以滿足樓主的需求。
參考http://www.cnblogs.com/lhb25/...
<code>var fd = new FormData; fd.append("username",document.querySelector("#username").value); fd.append("password",document.querySelector("#password").value); ... xhr.send(fd);</code>