服务器未通过ajax

时间:2015-10-28 04:15:17

标签: php ajax

我无法通过ajax将参数发送到服务器文件。我已经检查了comment.php,其中get参数工作正常。但是使用ajax post参数不会被comment.php接收,否则条件执行

请求内部标题的Payload显示服务器收到的url参数,但是当我回显$ _POST数组die(print_r($_REQUEST));时,它给我空数组

  

这是我正在使用的代码

 <input type="text" name="comment" id="q_comment" placeholder="Add a comment" onKeyPress="postComment('q_comment')" autocomplete="off">
<script>
function $(id){
    return document.getElementById(id);
}
document.onkeydown = function(event){
    key_code = event.keyCode;
}

function postComment(comment_type){ 
    if(key_code == 13){//If enter is pressed
        if(comment_type == "q_comment"){//if comment added in question
            var comment = $("q_comment").value;
        }
        else{//if comment added in answer
            var comment = $("a_comment").value;
        }
        if(comment != ""){          
            var question_id = "<?php echo $id; ?>";//Returns current question id
            //var params = "comment="+comment+"&question_id="+question_id;
            var params = "question_id="+question_id+"&comment="+comment;//data to send to server
            var ajax = new XMLHttpRequest();
            ajax.open("POST","/ajax_call_files/comment.php",true);
            ajax.setRequestHeader("Content-type","application/x-www-url-encoded");
            ajax.onreadystatechange = function(){
                if(ajax.readyState == 4 && ajax.status == 200){
                    var response = ajax.responseText;
                    console.log(response);
                }
            }
            ajax.send(params);
            console.log(params);
        }
    }   
</script>
  

Comment.php

if(isset($_POST['comment']) && isset($_POST['question_id']) && !empty($_POST['comment']) && !empty($_POST['question_id'])){
    require_once('../db_conn.php');
    $user_id = $_SESSION['id'];
    $comment = substr($_POST['comment'],0,530);
    $comment = htmlspecialchars($comment);
    $comment = mysqli_real_escape_string($conn,$comment);
    $question_id = preg_replace('#[^0-9]#','',$_POST['question_id']);

    $sql = "INSERT INTO comments(question_id,user_id,comment,date_time) VALUES('$question_id','$user_id','$comment',now())";
    $query = mysqli_query($conn,$sql);
    if($query){
        echo mysqli_insert_id($conn);
    }
    else{
        echo "Comment not added. Try again later";
    }
}
else{
    echo "no data recieved";
}

我在文件上重写规则,我正在调用ajax。可能是服务器没有收到url参数的原因 这是我正在使用的规则

RewriteRule ^questions/([0-9]+)/([a-zA-Z0-9_]+) questions.php?id=$1&title=$2 [NC,L]

2 个答案:

答案 0 :(得分:1)

更改行。

ajax.setRequestHeader("Content-type","application/x-www-url-encoded");

ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");

答案 1 :(得分:0)

之后

ajax.open("POST","/ajax_call_files/comment.php",true);

您需要将url参数添加为:

ajax.send(params);

在使用open()函数后的上述代码行之后,在设置了ajax调用的标题后

目前,您正在尝试在ajax调用之后将url参数发送到服务器