这是html程序...这里我使用ajax在文本字段输入一些数据后显示输出,它只是在food =''时只给出第一个响应,之后它没有显示另一个响应,就像我们没有'有。或者我们确实有。
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h1>choose your favorite food</h1>
<input type="text" id="inputuser">
<div id="usererror"></div>
</body>
</html>
这里是foodstore.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food=$_GET['food'];
$foodArray=array('shahi paneer','matar paneer','matar alu','raita');
if(in_array($food,$foodArray))
{
echo 'we do have '.$food.'!';
}
elseif($food=='')
{
echo 'please enter any dish';
}
else
{
echo 'we dont have '.$food.'!';
}
echo '</response>';
?>
这里是foodstore.js
var xmlHttp=createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if (window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(!xmlHttp)
alert("cant create that object");
else
return xmlHttp;
}
function process()
{
if (xmlHttp.readyState==0 ||xmlHttp.readystate==4)
{
dish=encodeURIComponent(document.getElementById("inputuser").value);
xmlHttp.open("GET","foodstore.php?food="+dish, true);
xmlHttp.onreadystatechange=handleServerResponse;
xmlHttp.send(null);
}
else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse=xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message=xmlDocumentElement.firstChild.data;
document.getElementById("usererror").innerHTML='<span style ="color:red">'+message+'</span>';
setTimeout('process()',1000);
}
else
{
alert('something went wrong');
}
}
}
答案 0 :(得分:0)
方法应该是
为文本框写入onchange事件(onchange of textbox content调用process()函数)。
or
- 醇>
添加按钮以触发该功能。 =&GT;用户进入菜肴并点击按钮。
接近一个(使用jQuery)
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<!--<script type="text/javascript" src="foodstore.js"></script>-->
<script>
$(document).on("keyup","#inputuser", function(){
var dish = $(this).val();
$.ajax({
type: "GET",
url: 'foodstore.php',
data : {food:dish},
success: function(data){alert(data);
$('#usererror').html(data);
}
});
});
</script>
</head>
<body>
<h1>choose your favorite food</h1>
<input type="text" id="inputuser" value="" />
<div id="usererror"></div>
</body>
</html>
foodstore.php
<?php
$food=$_GET['food'];
$foodArray=array('shahi paneer','matar paneer','matar alu','raita');
if(in_array($food,$foodArray)) {
echo 'we do have '.$food.'!';
}
elseif($food=='') {
echo 'please enter any dish';
} else {
echo 'we dont have '.$food.'!';
}
?>
答案 1 :(得分:0)
更改onload
上的onBlur
并从onload中移除并放入input
:
<input type="text" id="inputuser" onblur="process()">