AJAX POST无法使用document.getElementById变量

时间:2014-01-19 00:31:44

标签: javascript html ajax

我有一个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')";

2 个答案:

答案 0 :(得分:0)

Ajax数据的格式如下

data: {questionID: questionID, shortAnswerValue: shortAnswerValue, longAnswerText: longAnswerText},

data: {key:value, key2,"staticvalue"}

jQuery将构建进入URL末尾的字符串。

答案 1 :(得分:0)

你可以这样做:

data: encodeURI("questionID=" + questionID + "&shortAnswerValue=" + shortAnswerValue + "&longAnswerText=" + longAnswerText);

问题是var questionID中的空格,依此类推。此外,您在传递到$.ajax()的对象结束之前,在data属性值之后,还有一个不必要的逗号。