所以我是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:我想我必须以某种方式将数组传递给数据: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:错误是未定义的变量$ 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')");
}
答案 0 :(得分:2)
您只在AJAX数据中发送?
值。您还需要添加reply_txt
字段的值:
replyToPost
或者(最好)你可以使用var replyData = 'reply_txt=' + $(".replyText").val() + '&replyToPost=' + $('input[name="replyToPost"]').val();
让jQuery自动为你创建一个序列化的字符串:
serialize()
答案 1 :(得分:2)
您实际上可以将JS对象传递给ajax调用的l.append(s)
属性:
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);
}
});
});
中的代码仅用于演示/测试!
在SQL语句中使用未转义的$ _POST值非常危险