отправка получить через ajax javascript чистый ajax - PullRequest
0 голосов
/ 28 января 2019

Функция ajax находится в заголовке моей функции индексной страницы.

 myFunction(theVar) {

            var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

            var url = "includes/file.php";

            if (theVar.includes("postId")) {
                url = url + "?postId" + "=" + theVar.substr(theVar.length - 1);
            } else if (theVar.includes("userId")) {
                url = url + "?userId" + "=" + theVar.substr(theVar.length -1);
            } else if (theVar.includes("commentId")) {
                url = url + "?commentId" + "=" + theVar.substr(theVar.length -1);        
            }
            alert(url);


            xhr.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                  alert("Success!");
                }
              };
            xhr.open('GET', url, true);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.send();
            return xhr;
        }

Я получаю предупреждение об URL и об успешном выполнении функции, но идентификаторы не интерпретируются файлом file.php.

Может ли кто-нибудь помочь?

PHP-скрипт

<?php

    require ('connection.php');
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest") { 
        if (isset($_GET['postId']) && !empty($_GET['postId'])) { 
            $postId= mysqli_real_escape_string($link, 
            $_GET['postId']); 

            if (isset($postId) && !empty($postId)) { 
                mysqli_query = ($link, "UPDATE posts SET postVotes = postVotes + 1 WHERE postId = {$postId}"); 
            } 
        } 
    } else { die("You are not allowed to access this file..."); }
?>

Ответы [ 4 ]

0 голосов
/ 28 января 2019

Хорошо!Возникла проблема: мне

требуется файл в php-файле подключения

, а файл сценария php

не найден

файл

0 голосов
/ 28 января 2019

Кажется, что это особый способ структурировать переменную, особенно если учесть, что вам нужно дополнительно обработать ее, чтобы получить нужный идентификатор.Вы могли бы сделать это проще, как это?Преимущество этого состоит в том, что вы можете отправлять много параметров без необходимости изменять внутреннюю часть функции - просто добавьте больше параметров / значений к объекту переменной theVar.

html

<button type='button' onclick='myFunction( { postId:<?php echo $post['postId']; ?> } );'>Click me</button>

javascript

<script>

    const myFunction=function( theVar ) {
        var xhr=new XMLHttpRequest();
        var url = 'includes/file.php';

        var query=[];
        Object.keys( theVar ).map( function( key ){
            query.push( key+'='+theVar[key] )
        } );
        url+='?'+query.join('&');

        xhr.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              alert('Success!');
            }
          };
        xhr.open('GET', url, true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.send();
    }

</script>

Тем не менее, после незначительного редактирования ниже работало хорошо для меня только сейчас.Код PHP, который я использовал ниже, тоже ...

const myFunction=function( theVar ) {
    var xhr=new XMLHttpRequest();
    var url = 'includes/file.php';


    if (theVar.includes('postId')) {
        url = url + '?postId=' + theVar.substr(theVar.length - 1);
    } else if (theVar.includes('userId')) {
        url = url + '?userId=' + theVar.substr(theVar.length -1);
    } else if (theVar.includes('commentId')) {
        url = url + '?commentId=' + theVar.substr(theVar.length -1);        
    }       


    xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          alert('Success!');
        }
      };
    xhr.open('GET', url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.send();
}

Цель теста PHP

<?php

    echo json_encode( $_REQUEST );

?>

Ответ

{"postId":"4"}

Вы можете изменить PHP, чтобы сделатьэто немного более безопасно, используя подготовленные операторы.

<?php
    if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && !empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest" ) {

        require 'connection.php';

        $postId = filter_input( INPUT_GET, 'postId', FILTER_SANITIZE_NUMBER_INT );
        $commentId = filter_input( INPUT_GET, 'commentId', FILTER_SANITIZE_NUMBER_INT );
        $userId = filter_input( INPUT_GET, 'userId', FILTER_SANITIZE_NUMBER_INT );
        $sql=false;


        if( $postId ){
            $sql='update `posts` set `postVotes` = `postVotes` + 1 where postId=?;';
            $id=$postId;
        }

        /* assumed similar table called comments */
        if( $commentId ){
            $sql='update `comments` set `commentVote` = `commentVote` + 1 where `commentId`=?;';
            $id=$commentId;
        }

        /* etc - users too?? */
        if( $userId ){
            $sql='.... etc etc ';
            $id=$userId;
        }


        if( $sql ){
            $stmt=$link->prepare( $sql );
            $stmt->bind_param('i', $id );
            $res=$stmt->execute();
        }
    } else {
        exit( header( 'HTTP/1.1 403 Forbidden', true, 403 ) );
    }
?>

Полный, одна страница, демо

<?php
    if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && !empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest" ) {
        ob_clean();

        $postId = filter_input( INPUT_GET, 'postId', FILTER_SANITIZE_NUMBER_INT );
        $commentId = filter_input( INPUT_GET, 'commentId', FILTER_SANITIZE_NUMBER_INT );
        $userId = filter_input( INPUT_GET, 'userId', FILTER_SANITIZE_NUMBER_INT );
        /*
            here you would con
        */

        $output=array(
            'post'      =>  $postId,
            'comment'   =>  $commentId,
            'user'      =>  $userId
        );
        echo json_encode( $output );

        exit();
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>ajax</title>
        <style>
            body{display:flex;flex-direction:column;padding:1rem;margin:0;box-sizing:border-box;font-family:cursive;font-size:1rem;}
            div{display:flex;flex-direction:row;justify-content:center;align-content:space-between;align-items:center;flex:1;order:1;width:100%;}
            output{display:flex;flex:2;order:2;width:100%;justify-content:center;margin:1rem auto;}
            button{padding:1rem;margin:auto}

        </style>
        <script>
            const callback=function(r){
                if( r ){
                    document.querySelector( 'output' ).innerHTML=r;
                }
            };

            const myFunction=function(theVar){
                var xhr=new XMLHttpRequest();
                var url = location.href;

                if (theVar.includes('postId')) {
                    url = url + '?postId=' + theVar.substr(theVar.length - 1);
                } else if (theVar.includes('userId')) {
                    url = url + '?userId=' + theVar.substr(theVar.length -1);
                } else if (theVar.includes('commentId')) {
                    url = url + '?commentId=' + theVar.substr(theVar.length -1);        
                }
                xhr.onreadystatechange = function() {
                    if( this.readyState == 4 && this.status == 200 ) {
                        callback( this.response )
                    }
                };
                xhr.open('GET', url, true);
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                xhr.send();
            };

            const myOtherFunction=function( theVar ) {
                var xhr=new XMLHttpRequest();
                var url = location.href;

                var query=[];
                Object.keys( theVar ).map( function( key ){
                    query.push( key+'='+theVar[key] )
                } );
                url+='?'+query.join('&');
                xhr.onreadystatechange = function() {
                    if( this.readyState == 4 && this.status == 200 ) {
                        callback( this.response )
                    }
                };
                xhr.open('GET', url, true);
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                xhr.send();
            }
        </script>
    </head>
    <body>
        <div>
            <button type='button' onclick='myOtherFunction( { postId:808 } );'>Click me [POSTID]</button>
            <button type='button' onclick='myOtherFunction( { commentId:909 } );'>Click me [COMMENTID]</button>
            <button type='button' onclick='myOtherFunction( { userId:303 } );'>Click me [USERID]</button>
            <button type='button' onclick='myOtherFunction( { postId:808,commentId:909,userId:303 } );'>Click me [ALL]</button>
        </div>
        <div>
            <button type='button' onclick='myFunction( "postId808" );'>Click me [STRING - POSTID]</button>
            <button type='button' onclick='myFunction( "commentId909" );'>Click me [STRING - COMMENTID]</button>
            <button type='button' onclick='myFunction( "userId303" );'>Click me [STRING - USERID]</button>
        </div>
        <output></output>
    </body>
</html>
0 голосов
/ 28 января 2019

Я предполагаю, что переменная, которую вы передаете своей функции ajax, поступает таким образом, т.е. если ее postId она равна postId23, тогда вы, когда вы используете if (theVar.includes("postId"), проверяете, содержит ли она ключевые слова postIdзатем вы пытаетесь получить номер идентификатора, выполняя эту функцию theVar.substr(theVar.length - 1);. Здесь вы все перепутаете, потому что когда вы используете функцию substr(theVar.length-1);, она всегда будет возвращать последний символ в этой строке, так что если theVar равно postId23, то функцияsubstr () вернет 3 в качестве вашего идентификатора, затем вы получите URL-адрес как ?postId=3, но вы ожидали, что он вернет 23. Простой способ, если postId, commentId, userId являются константами, вам нужно будет знать, где заканчивается позиция строкового массива, т.е.если его postId в позиции, в которой он заканчивается, равен 5, то код функции substr () будет таким, как theVar.substr(5);, если строка - commentId, то считать конечную позицию строки массива, которая будет в позиции 8, тогда код будет theVar.substr(8);

Также это не очень хороший способ обработки запросов.Возможно, вам придется изменить способ отправки переменных в функцию и способ получения переменных.В будущем это может привести к ошибкам.Я надеюсь, что это поможет вам и всем остальным.

Попробуйте поиграть с этим примером функции substr() https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_substr

0 голосов
/ 28 января 2019

Ошибка здесь:

url = url + "commentId" + "=" + theVar.substr(theVar.length -1); 

Это должно быть:

url = url + "?commentId" + "=" + theVar.substr(theVar.length -1);

На стороне PHP вам нужно "перехватить" вашу переменную с помощью $_GET["commentId"]

Ссылка: http://php.net/manual/de/reserved.variables.get.php

Редактировать:

<?php
require ('connection.php');
if (isset($_GET['postId'])) { //  no need for && !empty($_GET['postId']) if isset is used
  $postId = mysqli_real_escape_string($link, $_GET['postId']);
  if (isset($postId)) { // no need for && !empty($postId) if isset is used
    //mysqli_query = ($link, "UPDATE posts SET postVotes = postVotes + 1 WHERE postId = {$postId}");
    echo "UPDATE posts SET postVotes = postVotes + 1 WHERE postId = {$postId}" // test
    }
    else {
      echo "postId is empty!";
    }
}

Теперь протестируйте его, используя, например, localhost/your.php?postId=2

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...