干得好。
这是您的表单的修改版本,让您开始了解方法和结果。只需运行此表格并查看回复如何返回并填写表格,然后您就可以对其进行调整。
这保存在一个名为“ajax_getting_specific.php”的文件中。ajax 向自身发出请求。
<?php
$formtext = isset($_POST['formtext'])? $_POST['formtext'] : null;
if (!empty($formtext) ){
/* When you understand how it works, use this kind of sql to get
* the data and show it back to the request. */
/*
$sql = "SELECT name,email,contact FROM datatable WHERE Name = '$formtext'";
$result = mysqli_query($db_conx, $sql);
if (mysqli_num_rows($result) === 1){
$data = mysqli_fetch_assoc($result);
echo $data['name'] . ":" . $data['Email'] .":". $data['Contact'];
} else {
echo "failed";
}
*/
/* This is just temporarily sending a sample response.*/
if($formtext !== null){
die("$formtext:$formtext@example.com:123456789");
} else {
die("failed");
}
}
?>
<script type='text/javascript'>
function getAjaxRequest() {
var username = document.getElementById('formtext1').value;
/* request to itself */
var ajax = ajaxObj('POST', 'ajax_getting_specific.php');
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != 'failed'){
// This part is populating the fields based on what came back
var fields = ajax.responseText.split(":");
alert (fields[0] + " - " + fields[1] + " - " + fields[2]);
document.getElementById('ajax-response').innerHTML = ajax.responseText;
document.getElementById('formtext2').value = fields[1];
document.getElementById('formtext3').value = fields[2];
document.getElementById('name-display').innerHTML = fields[0];
document.getElementById('email-display').innerHTML = fields[1];
document.getElementById('contact-display').innerHTML = fields[2];
} else {
document.getElementById('ajax-response').innerHTML = "AJAX FAILED";
}
}
}
ajax.send('formtext=' + username);
}
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
</script>
Fetching fields from table based on the first entry
<br>
<div id='ajax-response'>AJAX response will appear here</div>
<br><br>
<input id="formtext1" name="formtext1" type="text" style="width:200px;left:140px;top:120px;z-index:2">
<button name="formbutton1"
onclick="getAjaxRequest()" value="GO" style="left:140px;top:140px;z-index:3">GO</button>
<form name="form1" style="margin:0px">
<input id="formtext2" name="formtext2" type="text" style="width:200px;left:140px;top:180px;z-index:5">
<input id="formtext3" name="formtext3" type="text" style="width:200px;left:140px;top:240px;z-index:7">
</form>
<div id="text1">
<div class="wpmd">
<div>Name: <span id="name-display" style="z-index:1"></span></div>
</div>
</div>
<div id="text2">
<div class="wpmd">
<div>Email: <span id="email-display"></span></div>
</div></div>
<div id="text3">
<div class="wpmd">
<div>Contact: <span id="contact-display"></span></div>
</div></div>