做Ajax
的示例,文本框中的用户类型及其文本使用javascript连续发回,同时显示结果是否可用。
主 html 外观如
<body>
<h3>The chuff Bucket </h3>
Enter the food you like to order:
<input type="text" id="userInput" onfocus="process()"/>
<div id="underInput"/>
</body>
这是我的javascript代码
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp) {
alert("cant create that object boss!");
} else
return xmlHttp;
}
function process() {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET", "foodstore.aspx?food=" + food, 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("underInput").innerHTML = '<span style = "color:blue;">' + message + '</span>';
setTimeout('process()', 1000);
} else {
alert('Something went wrong');
}
}
}
php的代码工作正常,
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array("tuna","bacon","beef","mutton","biryani");
if($food == '')
echo 'Enter a food you idiot.';
else{
if(in_array($food,$foodArray))
echo 'We do have '.$food.'!';
else
echo 'We do not sell '.$food.'!';
}
echo '</response>';
?>
但是当转换为asp.net时,它是回发并且正在工作但没有在div中显示reult。我找出相关回声线的主要原因
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/xml";
System.Diagnostics.Debug.Print("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>");
System.Diagnostics.Debug.Print("<response>");
string food = (string)Request.QueryString["food"];
string[] foodArray = new string[] { "tuna", "beef", "mutton", "fish","biryani" };
if (String.IsNullOrEmpty(food))
{
System.Diagnostics.Debug.Print("Enter a food you idiot.");
}
else
{
if (foodArray.Contains(food))
{
System.Diagnostics.Debug.Print("We serve " + food);
}
else
{
System.Diagnostics.Debug.Print("We do not serve " + food);
}
}
System.Diagnostics.Debug.Print("</response>");
}
注意:我已经尝试过而不是Print
Response.Write
,但结果与id = underInput得不到结果的div相同。有人在这里帮忙。
答案 0 :(得分:-1)
确保已使用Response.Write替换了所有System.Diagnostics.Debug.Print。然后,检查foodstore.aspx上的HTML标记。
Foodstore.aspx应该有@Page指令,但没有别的..你想要返回XML内容,所以你需要确保页面上没有DOCTYPE或HTML元素。