2012-01-10 75 views
-3

该页面有一个textbox和一个submit按钮。该文本框接受一个项目。在添加项目时,页面上的列表应刷新并使用ajax显示新项目。使用html表单和ajax刷新页面上的列表

以前的项目应该保留。

到目前为止,我写的代码: 1)123.html:

<html> 
<head> 
<title>PHP using AJAX</title> 
<script type="text/javascript"> 

var time_variable; 

function getXMLObject() //XML OBJECT 
{ 
    var xmlHttp = false; 
    try { 
    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers 
    } 
    catch (e) { 
    try { 
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+ 
    } 
    catch (e2) { 
     xmlHttp = false // No Browser accepts the XMLHTTP Object then false 
    } 
    } 
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { 
    xmlHttp = new XMLHttpRequest();  //For Mozilla, Opera Browsers 
    } 
    return xmlHttp; // Mandatory Statement returning the ajax object created 
} 

var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object 

function ajaxFunction() { 
    var getdate = new Date(); //Used to prevent caching during ajax call 
    if(xmlhttp) { 
    var txtname = document.getElementById("txtname"); 
    xmlhttp.open("POST","321.php",true); //calling 321.php using POST method 
    xmlhttp.onreadystatechange = handleServerResponse; 
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
    xmlhttp.send("txtname=" + txtname.value); //Posting txtname to PHP File 
    } 
} 

function handleServerResponse() { 
    if (xmlhttp.readyState == 4) { 
    if(xmlhttp.status == 200) { 
     document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element 
    } 
    else { 
     alert("Error during AJAX call. Please try again"); 
    } 
    } 
} 
</script> 
<body> 
<form name="myForm"> 
<table> 
<tr> 
    <td>Enter Name</td> 
    <td><input type="text" name="txtname" id="txtname" /></td> 
</tr> 
<tr> 
    <td colspan="2"><input type="button" value="Submit" onclick="ajaxFunction();" /></td> 
</tr> 
</table> 
<div id="message" name="message"></div> 
</form> 
</body> 
</head> 
</html> 

2)321.php

<?php 

$a = $_POST["txtname"]; 

echo ".$a."; 
?> 

我能够得到物品的输出列表(什么我在文本框中输入)而不刷新。 想知道我可以如何添加到列表中保持以前的项目完好无损。即更新列表保持前面的输出 谢谢。

+1

你有什么这么远吗?你真的需要展示一些HTML和JS让我们能够帮助你。 – PeeHaa 2012-01-10 17:26:23

+1

尝试写一些自己。看看你想出什么。你似乎有一个好主意需要发生。我们不是在这里为你写的,只是为了帮助你解决问题。 – idrumgood 2012-01-10 17:27:00

+0

代码正常工作,无需刷新显示页面上的项目。只是想知道我需要对php(或js)所做的更改,如果我想保留之前项目的输出并在每次更新时添加到列表中。 – prit2192 2012-01-10 17:50:12

回答