在通过ajax Json格式提交时在mysql中插入查询问题

时间:2014-05-07 10:32:39

标签: php mysql json

我正在开发一个网站,我将数据通过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'};

1 个答案:

答案 0 :(得分:2)

好的,我明白你在做什么。你不需要这样做。这是您问题的简化版本,向您展示如何实现ajax帖子:

<强> 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>

输出:

enter image description here


因此,当请求发生时,data字段及其值在php中可用,如下所示:

$comment = isset($_POST['comment']) ? $_POST['comment'] : '';
$postID = isset($_POST['postID']) ? $_POST['postID'] : '';

希望这有帮助。