dos49618
dos49618
2017-12-19 04:51
浏览 61

从js脚本将数据发送到当前的php文件

I have a php file, content.php, that is currently being loaded in the browser:

<html>
    <head>
        <title>Content</title>

        <script src="content.js"></script>
    </head>

    <body>
        <?php
            if ( isset($_POST["status"]) && ($_POST["status"] === 1) ) {
        ?>

            Content for users with status 1

        <?php
            } else {
        ?>

            Content for users with different status

        <?php
            }
        ?>
    </body>
</html>

What I want to do, is set the

$_POST["status"]

variable from within

content.js

I have thought about using a hidden html form and clicking the submit button through javascript, but that doesn't really seem like an elegant solution.

I have also thought about using an XMLHttpRequest, the problem being that I haven't found a way to send the data to the currently viewed/loading page through an XMLHttpRequest.

I am using no extra libraries, only javascript and php.

Is there a more elegant solution to my problem the a hidden html form?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongwen1935
    dongwen1935 2017-12-19 06:28
    已采纳

    Seems you need to work with AJAX because you need to execute server side script in hidden manner and update the html.

    1. interface.php has content.js and a div
    2. content.js send ajax post request with status
    3. content.php sends the content according to status
    4. interface.php's div is updated.

    Here are the content.js and interface.php

    let status = 1;
    loadDoc(status);
    
    function loadDoc(status) {
      let xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = () => {
        if (xhttp.readyState == 4 && this.status == 200) {
          document.getElementById("content").innerHTML =
          xhttp.responseText;
        }
      };
      xhttp.open("POST", "content.php", true);
      xhttp.send("status=" + status);
    }
    <html>
        <head>
            <title>Content</title>
            <script src="content.js"></script>
        </head>
    
        <body>
           <div id="content"></div>
        </body>
    </html>

    And here is your content.php

    <?php
        if ( isset($_POST["status"]) && ($_POST["status"] === 1) ) {
    ?>
    
        Content for users with status 1
    
    <?php
        } else {
    ?>
    
        Content for users with different status
    
    <?php
        }
    ?>
    

    Bingo! You set the $_POST["status"] via content.js

    </div>
    
    点赞 评论
  • doutang0335
    doutang0335 2017-12-19 04:56

    POST variables can only be passed in a request header. This means that it has to be either a form submission, as you already know, or an AJAX request. There is no way to have a separate client-side resource supply new information to an existing request.

    点赞 评论

相关推荐