首页 > 解决方案 > 发送通过ajax javascript 纯ajax

问题描述

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 的警报,并且在触发函数时成功但 id 不被 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..."); }
?>

标签: javascriptphpajax

解决方案


这似乎是构造变量的一种特殊方式,特别是考虑到您需要进一步处理它以获得所需的 ID。你可以像这样让它更简单吗?这样做的好处是您可以发送许多参数而无需修改函数的内部部分 - 只需向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>

推荐阅读