使用ajax将文本值传递给另一个php文件

时间:2016-03-01 19:17:48

标签: javascript php jquery ajax

我编写了一个包含文本框和提交按钮的代码。当我按下带有文本框值的输入时,它应该使用ajax转到另一个页面(q.php),它应该从那里返回值到这里(home.php) 这是我的代码。 (home.php)

 <!DOCTYPE html>
 <html>
 <head>
<script>
function myFunction(str) {
  if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
  }
  if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
  xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
  document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
  xmlhttp.open("GET","q.php?q="+str,true);
   xmlhttp.send();
 }
</script>
</head>
<body>

 <form onsubmit="return myFunction(document.getElementById('fname'))">
  Enter name: <input type="text"id="fname" name="fname">
 <input type="submit" value="Submit">
 </form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
 </body>
 </html>

我的下一页(q.php)

<?php
 $q = $_GET['q'];
 echo $q."Some Content from this page";
 ?>

1 个答案:

答案 0 :(得分:0)

我的回答是使用html+jquery+php: -

<html>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script><!-- add jquery library -->
<form method="post">
Enter name: <input type="text"id="fname" name="fname">
<input type="submit" value="Submit" class= "abc">
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
 </body>
 </html>
<script type = "text/javascript">
$(document).ready(function(){ //when your page is rendered completly
    $('.abc').click(function(e){ //when you click on submit button this function will run
        e.preventDefault();//to prevent normal submission of form
        if($('#fname').val() !== ''){ //check name field have some value
            $.post('q.php',{'q':$('#fname').val()},function( data ){ //send value to post request in ajax to the php page
                $('#txtHint').html(data); //print the response coming from php page to the result div inside your html code
            });
        }
    });

});
</script>

在php文件中: -

<?php
 $q = $_POST['q'];
 echo $q."Some Content from this page";
 ?>