dos49618 2017-12-19 04:51
浏览 62
已采纳

从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 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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3