[英]AJAX POST Won't Work With document.getElementById Variables
我有一個HTML表單和ajax調用,可通過PHP頁面將數據存儲在MySQL中。
這三個代碼都復制到下面。 (請注意//)
只要我在ajax調用存儲它們的函數中對變量進行了硬編碼,這三個函數就可以正常工作。 但是,當我注釋掉硬編碼的變量並使用常規變量運行它時,它將不起作用。
JavaScript AJAX調用$(“#buttonSubmit”)。click(function(){
//var questionID = obj.Questions[i].questionID;
//var shortAnswerValue = document.getElementById('txtShortAnswerValue').value;
//var longAnswerText = document.getElementById('txtLongAnswerText').value;
var questionID = "SampleQID";
var shortAnswerValue = "Sample Short";
var longAnswerText = "Sample Long";
$.ajax({
type: "POST",
url: "SaveUpdatesTemplate.php",
data: "questionID=" + questionID + "&shortAnswerValue=" + shortAnswerValue + "&longAnswerText=" + longAnswerText,
}); // end ajax function
document.getElementById("txtLongAnswerText").reset();
}); // end button submit function
關聯的HTML選擇檢查或項目階段選擇檢查或項目階段
<label for="selectSection">Select Inspection or Project Phase</label>
<select class="form-control" id="selectSection" name="selectSection">
<option> Select Inspection or Project Phase</option>
</select>
<button type="button" class="form-control" id="buttonStart" name="buttonStart" value="List Questions">Start - Click to Populate Question List</button>
<label for="selectQuestion">Select Task or Question to Update</label>
<select class="form-control" id="selectQuestion" name="selectQuestion" >
<option> Select Task or Question to Update </option>
</select>
<!-- short answer below -->
<label for="txtShortAnswerValue">Short Answer</label>
<select class="form-control" id="txtShortAnswerValue" name="txtShortAnswerValue">
<option value="1" selected>worst</option>
<option value="3">middle</option>
<option value="5">best</option>
</select>
<!-- long answer below -->
<label for="txtLongAnswerText">Long Answer / Notes</label>
<textarea class="form-control" name="txtLongAnswerText" id="txtLongAnswerText" rows=3>
</textarea>
關聯的PHP代碼//將PHP變量分配給客戶端的POST結果
$questionID = htmlspecialchars(trim($_POST['questionID']));
$shortAnswerValue = htmlspecialchars(trim($_POST['shortAnswerValue']));
$longAnswerText = htmlspecialchars(trim($_POST['longAnswerText']));
//SQL STATEMENT
$sql="INSERT INTO Updates (questionID, shortAnswerValue, longAnswerText)
VALUES
('$questionID', '$shortAnswerValue', '$longAnswerText')";
Ajax數據的格式如下
data: {questionID: questionID, shortAnswerValue: shortAnswerValue, longAnswerText: longAnswerText},
要么
data: {key:value, key2,"staticvalue"}
jQuery將構建URL末尾的字符串。
您可以這樣做:
data: encodeURI("questionID=" + questionID + "&shortAnswerValue=" + shortAnswerValue + "&longAnswerText=" + longAnswerText);
問題是var questionID
的空格,依此類推。 另外,在傳遞給$.ajax()
的Object末尾( $.ajax()
data
屬性值之后$.ajax()
,您還有一個不必要的逗號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.