【发布时间】:2014-05-16 14:21:24
【问题描述】:
以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 内显示结果。我找出相关回声线的主要原因
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 相同,但没有得到结果。请在这里的任何人提供帮助。
【问题讨论】:
标签: c# javascript php asp.net ajax