通过ajax发送获取javascript纯ajax

时间:2019-01-28 07:42:27

标签: javascript php ajax

ajax函数位于我的索引页面的标题中 功能。

<LinearLayout 
    android:orientation="horizontal">
  <ImageView 
     android:layout_width="0dp"
     android:layout_weight="1" // try to read about this parameter more
  />
  <LinearLayout
     android:layout_width="0dp"
     android:layout_weight="4"
     android:orientation="vertical">

    <TextView ... />
    <TextView ... />
    <TextView ... />
  </LinearLayout>
</LinearLayout>

我收到有关URL的警报,并在触发函数时成功,但file.php无法识别ID。

有人可以帮忙吗?

PHP脚本

 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;
        }

4 个答案:

答案 0 :(得分:0)

错误在这里:

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

对其进行测试

答案 1 :(得分:0)

这似乎是构造变量的一种特殊方法,特别是考虑到您需要进一步处理它以获得所需的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>

答案 2 :(得分:0)

我假设您要传递给ajax函数的变量以这种方式出现,即,如果其变量postIdpostId23出现,那么当您使用if (theVar.includes("postId")来检查它时包含关键字postId,然后尝试通过执行此功能来获取ID号theVar.substr(theVar.length - 1);,这是您搞砸的地方,因为当您使用函数substr(theVar.length-1);时,它将始终返回其中的最后一个字符字符串,因此,如果theVarpostId23,函数substr()将返回3作为您的id,那么您将获得的URL为?postId=3,但您希望它返回23。 ,commentId,userId是常量,您将必须知道字符串数组位置的结束位置,即如果其postId的结束位置为5,则如果字符串为commentId,则函数substr()代码将为theVar.substr(5);计算数组字符串的结束位置,该位置将位于位置8,则代码将为theVar.substr(8);

这也不是处理请求的好方法。您可能必须更改将变量发送到函数的方式以及如何获取变量。将来可能会导致错误。希望对您和其他人有帮助。

尝试使用有关substr()函数https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_substr

的示例进行游戏

答案 3 :(得分:0)

好!我有一个问题

  

需要连接php文件中的文件

和php脚本文件

  

找不到

文件