我正在开发一个网站,我通过ajax以Json格式将数据插入到php页面,然后解码后将其发送到mysql数据库,但是如果我的字符串包含< > || & ' "
字符,然后我的网页给出 php 错误。那么我应该如何进一步进行。它不允许插入一些特殊字符..
var obj = {"comment": commentText, "postID": postID};
var commentData = 'commentData=' + JSON.stringify(obj);
$.ajax({
type: "POST",
url: addNewCommentsUrl,
datatype: 'json',
data: commentData,
cache: false,
beforeSend: function() {
// $(document.body).off('click','.postComment');
},
success: function(result) {
commentBox.val("");
commentHolder.append(result);
// jQuery("#all-posts").masonry('reloadItems');
jQuery('#all-posts').masonry('layout');
var count = parseInt(parent.find("#commentContainer").text());
parent.find("#commentContainer").html(++count);
// $(document.body).on('click','.postComment');
}
});// end of ajax
在 php 端
$recievedData = $_POST['commentData'];
$recieveddatajson = json_decode($recievedData);
$lastCommentID = $recieveddatajson->{'commentID'};
$parentPostID = $recieveddatajson->{'postID'};
最佳答案
好的,我明白你在做什么。你不需要这样做。这是您的问题的简化版本,向您展示如何实现 ajax post:
test.php
<?php
// Handle Post
if (count($_POST))
{
echo "You posted\r\n";
print_r($_POST);
exit();
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "test.php",
data: { "comment": "hello world", "postID": 1234 },
// data: { "comment": commentText, "postID": postID },
success: function(result) {
alert("Server Said:\r\n" + result);
}
});
});
</script>
输出:
<小时/>
因此,当请求发生时,data
字段及其值在 php 中可用,如下所示:
$comment = isset($_POST['comment']) ? $_POST['comment'] : '';
$postID = isset($_POST['postID']) ? $_POST['postID'] : '';
希望这有帮助。
关于php - 通过ajax Json格式提交时在mysql中插入查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23515351/