简体   繁体   English

如何在“提交”或“输入”按钮上提交表单

[英]How to submit a form on SUBMIT or ENTER button

I am trying to follow a tutorial and demo . 我正在尝试按照教程演示进行操作 But when I press SUBMIT or ENTER button, it is not submitting, it is just refreshing the page :( and showing an error. 但是,当我按SUBMIT或ENTER按钮时,它没有提交,只是刷新页面:(并显示错误。

It shows an alert 显示警报

There was a problem with the request. 这个要求有个问题。

And the page refreshes. 然后页面刷新。

My form 我的表格

<form class="well-home span6 form-horizontal" name="ajax-demo" id="ajax-demo"> <div class="control-group">
              <label class="control-label" for="book">Book</label>
              <div class="controls">
                <input type="text" id="book" onKeyUp="book_suggestion()">
                <div id="suggestion"></div>
             </div>  </div>  <div class="control-group">
              <div class="controls">
                <button type="submit" class="btn btn-success">Submit</button>
              </div>  
       </div> 
</form>

And my Javascript 还有我的Javascript

<script>
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
 if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
     xhr.open("POST", "book-suggestion.php", true); 
     xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  
     xhr.send(data);
     xhr.onreadystatechange = display_data;
    function display_data() {
     if (xhr.readyState == 4) {
      if (xhr.status == 200) {
       //alert(xhr.responseText);      
      document.getElementById("suggestion").innerHTML = xhr.responseText;
      } else {
        alert('There was a problem with the request.');
      }
     }
    }
}
</script>

book-suggestion.php book-suggestion.php

<?php  
include('../includes/dbopen.php');  
$book_name = $_POST['book_name'];  
$sql = "select book_name from book_mast where book_name LIKE '$book_name%'";  
$result = mysql_query($sql);  
while($row=mysql_fetch_array($result))  
{  
echo "<p>".$row['book_name']."</p>";  
}  
?>  

The submit button used there is not participating in the demo. 此处使用的提交按钮未参与演示。 The purpose of the demo is to show how to fetch data with ajax when user types data in the text box . 该演示的目的是演示当用户在文本框中键入数据时如何使用ajax获取数据。 It may, for sure be extended so that the submit button acts upon and adds some more functions, but for now, that has not been added to the demo. 可以肯定地将其扩展,以使“提交”按钮起作用并添加一些其他功能,但是到目前为止,该功能尚未添加到演示中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM