我现在已经敲了几个小时。我有一个选择选项,它使用AJAX更新数据库(至少它正在尝试!)。发生的事情是直接使用params运行PHP脚本需要数据库更新但不是通过AJAX间接运行时,而是获得alert("There was a problem in the returned data:\n");
的3倍然后它会更新。 JavaScript在<head>
上,而不在外部文件中。在这里:
JavaScript的:
function updateHub(){
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("hubinfo").innerHTML=xmlhttp.responseText;
}else{
alert("There was a problem in the returned data:\n");
}
}
var prefHub = document.getElementById("prefHub");
var hubID = prefHub.options[prefHub.selectedIndex].value;
xmlhttp.open("GET","updateHub.php?hubID="+hubID,true);
xmlhttp.send();
}
updateHub.php:
session_start();
include '../../../common/config.php';
$hubID = '';
if(isset($_POST['hubID'])){
$hubID = strip_tags(mysql_real_escape_string(trim($_POST['hubID'])));
}elseif(isset($_GET['hubID'])){
$hubID = strip_tags(mysql_real_escape_string(trim($_GET['hubID'])));
}
mysql_query("UPDATE prefs set hubID='$hubID' where userID = '".$_SESSION['userID']."'") or die(mysql_error());
if(mysql_affected_rows()){
echo "Updated";
}else{
echo 'Error';
}
return $hubID;
和HTML:
<form action="" method="post" onsubmit="updateHub();">
<select name="prefHub" id="prefHub">
<option value="43">opt1</option>
<option value="64">opt2</option>
<option value="30">opt2</option>
</select>
<input type="submit" name="update" value="Update Hub"/>
</form>
<div id="hubinfo"></div>
答案 0 :(得分:2)
相反,我获得了警报的3倍(“那里 回来是一个问题 数据:\ n“);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("hubinfo").innerHTML=xmlhttp.responseText;
}
else{
alert("There was a problem in the returned data:\n");
}
这意味着您将始终看到警报。因为对于任何其他xmlhttp.readyState值,将执行else {}块。
XMLHttpRequest对象可以处于多种状态。 readyState属性必须返回当前状态,该状态必须是以下值之一:
UNSENT(数值0)
The object has been constructed.
OPENED(数值1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.
HEADERS_RECEIVED(数值2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
LOADING(数值3)
The response entity body is being received.
完成(数值4)
答案 1 :(得分:0)
我搬了
var prefHub = document.getElementById("prefHub");
var hubID = prefHub.options[prefHub.selectedIndex].value;
之后
function updateHub()
{
并删除
else{
alert("There was a problem in the returned data:\n");
}
它现在正常工作,但我不明白为什么。是否有人能够解释它?
andreas解释了原因。