Ajax生成的表单在初始请求后不发送更新的值


Ajax generated form not sending updated values after initial request

我知道这里有更实用的方法来实现我想要实现的目标,但如果可能的话,我需要坚持这个模型。

我正在尝试将多个HTML文本输入字段中的值发送到Javascript函数。它在第一次提交时按预期工作。每次Ajax将表单重新加载到容器div之后,它都会发送原始提交的值,而不是更新后的值。我该怎么解决这个问题?

这是进行调用的地方:(drawNewEvent.php的结果输出显示在Div标记中)

<? $cal = $_POST['cal']; ?>
<button type="button" onClick="newEvent(<? echo $cal['KEY']; ?>)">Add Event</button>
<div id="container">
<!--Form goes here-->
</div>

这是我正在使用的Ajax函数:

function newEvent(calID){
    var xmlhttp;
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("container").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","cal/draw/drawNewEvent.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("calID="+calID);
}

drawNewEvent.php:

<? $calID = $_POST['calID']; ?>
<h1> Add Event to <? echo $calID;?></h1>
<table border="1"><tr><td>
<br>
<table>
<tr>
<td>Event name:</td><td><input name="name" type="text" id="aname" size="32" maxlength="40" /></td>
</tr><tr>
<td>Date:</td><td><input name="date" type="text" id="date" maxlength="10" value="<?php echo date('Y-m-d'); ?>"/> (YYYY-MM-DD)</td>
</tr><tr>
<?php $hour = date('H'); $hour -= 4;?>
<td>Starting Time:</td><td><input name="sTime" type="text" id="sTime" maxlength="8" value="<?php echo $hour.date(':i'); ?>"/> (HH:MM)</td>
</tr><tr>
<td>Ending Time:</td><td><input name="eTime" type="text" id="eTime" maxlength="8" value="<?php echo ($hour+1).date(':i'); ?>"/> (HH:MM)</td>
</tr>
<tr>
<td>Location:</td><td><input name="location" type="text" id="alocation" size="32" /></td>
</tr>
<tr>
<td>Notes:</td><td><textarea name="notes" id="notes"  rows="10" cols="30"/></textarea></td>
</tr>
</table>
<button type="button" name="add" 
onClick="addEvent(aname.value, date.value, sTime.value, eTime.value, alocation.value, notes.value, <?php echo $calID ?>)">Add Event </button>
</td></tr></table>

调用的函数只显示给定的输入:

function addEvent(name, date, sTime, eTime, location, notes, calID){
    alert("name: "+name + "'nDate: " + date + "'nTime: " + sTime + "-" + eTime + "'n Location: " + location + "'n Notes: " + notes + "'n CalID = " + calID);
}

好吧,你的calID总是一样的(应该是吗?)。您正在发送一个在URL中具有相同参数的ajax请求,很可能第二次收到缓存响应,因此第二次ajax请求永远不会通过服务器运行。我建议通过使用随机变量或更改变量来避免缓存。例如:

var d = new Date();
var n = d.getTime();
xmlhttp.open("POST","cal/draw/drawNewEvent.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("calID="+calID+"&random="+n);

现在,浏览器将您的ajax请求视为不同的请求,并且不会从缓存中返回。让我们从这里调试。你的剧本现在表现如何?