我想從我有的表單中獲取隱藏的輸入值。除了HIDDEN元素外,表單正確傳遞所有元素。我知道他們被聲明,因爲如果我選擇頁面上的「查看源代碼」,它會向我顯示正確的值(基本上是用戶憑據)。javascript無法從HTML輸入標記分配隱藏的輸入元素
<form name="addExperienceForm" id="addExperienceForm" style="display:none;">
Title:<input type="text" name="title" id="title" />
From:<input type="text" name="startDate" id="startDate" />
To:<input type="text" name="endDate" id="endDate" />
Description:<textarea type="message" name="description" id="description"></textarea>
<input type="button" value="Submit" onclick="addUserExp()"/>
<input type="hidden" value="<?=$_SESSION['userID']?>" id="userID" />
<input type="hidden" value="<?=$_SESSION['email']?>" id="email" />
function addUserExp(){
//get info
var title = document.getElementById('title').value;
var startDate = document.getElementById('startDate').value;
var endDate = document.getElementById('endDate').value;
var userID = document.getElementById('userID').value;
var email = document.getElementById('email').value;
var description = document.getElementById('description').value;
//construct POST string with name value pair
var str = "title="+title+"start="+startDate+"end="+endDate+"userID="+userID+"email="+email+"desc="+description;
//establish XMLHTTP object
var req = getXMLHTTP();
if(req){
req.onreadystatechange = function(){
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('addNewExp').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
}
req.open("post", "addExperience.php", true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(str);
}
PHP
<?php
$title = $_POST['title'];
$startDate = $_POST['start'];
$endDate = $_POST['end'];
$userID = $_POST['userID'];
$email = $_POST['email'];
$description = $_POST['desc'];
$sql = "INSERT INTO `user_experience`(`user_id`, `email`, `experience_title`, `experience_desc`, `start_date`, `end_date`)
VALUES ('$userID', '$email', '$title', '$startDate', '$endDate', '$description')";
echo $sql;
?>
我呼應了MYSQL語句,這樣你可以看到,沒有被填充的字段。的上述輸出端產生數據時輸入到表單的情況如下:
INSERT INTO `user_experience`(`user_id`, `email`, `experience_title`, `experience_desc`, `start_date`, `end_date`) VALUES ('', '', 'test', 'Feb-2013', 'May-2013', 'test')
你確定這些元素的值是由生成表單(查看源代碼)的PHP設置的嗎?你在迴應他們的應該接受他們的PHP,你有沒有嘗試在瀏覽器中回顯他們,然後再發送AJAX查詢以查看JS是否正確讀取了'.value'?假設用戶標識和電子郵件已存儲在會話中,並且處理AJAX的腳本位於同一個PHP實例中,那麼是不是可以在處理AJAX的腳本中使用'$ _SESSION'而不是將它們傳遞給查詢? +1,因爲這不是一個壞問題。 –