所以我是新的ajax,我正面临着一个问题,从我的表单得到所有的值。
我想插入名称reply_txt和$ newsId到我的表
html表单:<form>
<input type="hidden" name="replyToPost" value="<?php echo $newsId;?>">
<textarea name="reply_txt" class="replyText"></textarea>
<button class="replySubmit">Answer</button>
</form>
ajax:我想我必须以某种方式传递一个数组到data:replyData
$(".replySubmit").click(function(event){
event.preventDefault();//prevent action from button
var replyData = 'reply_txt='+ $(".replyText").val(); //build a post data structure
$.ajax({
type: "POST", // POST type
url: "response.php", //call ajax on page
dataType:"text", //type of data html/ajax/jason ...
data:replyData, //Form variables intups
success:function(response){
$(".respondsReply").append(response);
$(".replyText").val(''); //empty text field on successful
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
response.php: error is undefined变量$newsId
if(isset($_POST["reply_txt"]) && strlen($_POST["reply_txt"])>0){
$replyToSave = filter_var($_POST["reply_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$newsId = $_POST["replyToPost"];
$userId = $_SESSION['userId'];
$reply_row = $db->query("INSERT INTO replyPost(message,newsId_fk,userId_fk) VALUES('$replyToSave','$newsId','$userId')");
}
可以将JS对象传递给ajax调用的data
属性:
$(".replySubmit").click(function(event){
event.preventDefault();//prevent action from button
// Build the data object for ajax request:
var replyData = {
"reply_txt" : $(".replyText").val(),
"replyToPost": $("input[name=replyToPost]").val()
};
$.ajax({
type: "POST", // POST type
url: "response.php", //call ajax on page
dataType: "text", //type of data html/ajax/jason ...
data: replyData, //data object
success: function(response){
$(".respondsReply").append(response);
$(".replyText").val(''); //empty text field on successful
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
我也希望response.php
中的代码仅用于演示/测试!在SQL语句中使用未转义的$_POST值是极其危险的
您只发送AJAX数据中的reply_txt
值。您还需要添加replyToPost
字段的值:
var replyData = 'reply_txt=' + $(".replyText").val() + '&replyToPost=' + $('input[name="replyToPost"]').val();
或者(最好)你可以使用serialize()
让jQuery自动为你创建一个序列化字符串:
$(".replySubmit").click(function(event){
event.preventDefault(); //prevent action from button
$.ajax({
type: "POST", // POST type
url: "response.php", //call ajax on page
dataType: "text", //type of data html/ajax/jason ...
data: $(this).serialize(), //Form variables intups
success:function(response){
$(".respondsReply").append(response);
$(".replyText").val(''); //empty text field on successful
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});