我如何获得一个JavaScript对象是创建在另一个php文件由第一页


How do I obtain a JavaScript object that is created on another php file made by the first page?

我的问题是我需要访问在另一个页面(php文件)上创建的JavaScript对象,并在我当前的页面中使用它。

所以,这是我的第一个页面test_ong.php包含两个按钮。一种是创建另一个页面来生成JavaScript对象,另一个按钮来检索JavaScript对象。

<button id="new">Open New Win</button>
<button id="dis">Display</button>
<div id="test"></div>
<script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>
<script type="text/javascript"> 
var myChild;
$("#new").click(function() {
    myChild = window.open("test_reg.php","","width=500, height=500, resizable=yes");
});
$("#dis").click(function() {
    console.log('I clicked this');
    $.post("test_reg.php", function(data) {
        console.log(data);
    });
});
</script>

第二个页面test_reg.php,它将创建对象whatIWant .

<script type="text/javascript">
    var whatIWant = {
        fruit: "apple",
        car: "Lotus",
        age: 31,
        hobby: "coding"
    };
</script>

我想要的是每当我点击按钮显示。它将给我控制台日志中的对象whatIWant

我知道我可以通过使用myChild.whatIWant得到这个,但我需要刷新我的第一页,仍然得到对象myChild.whatIWant

感谢你阅读或回答我的问题。

第二页应该只返回如下对象:

 {
        fruit: "apple",
        car: "Lotus",
        age: 31,
        hobby: "coding"
 }

您可以通过ajax调用,您需要首先初始化一个变量,然后通过ajax调用,您可以重写它,然后再次显示

<!DOCTYPE html>
    <html>
      <head>
        <link rel="stylesheet" href="style.css">
        <script>var whatIWant = {};</script>
      </head>
 <body>
    <button id="new">Open New Win</button>
    <button id="dis">Display</button>
    <div id="test"></div>
    <script
      src="https://code.jquery.com/jquery-3.1.1.min.js"
      integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
      crossorigin="anonymous"></script>
    <script type="text/javascript"> 
    var myChild;
    $("#new").click(function() {
        myChild = window.open("test_reg.php","","width=500, height=500, resizable=yes");
    });
    $("#dis").click(function() {
        console.log('I clicked this');
        $.ajax({
                type: "POST",
                url: "test_reg.php",
                data: {},
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                   alert(data);
                },
                error: function (errormessage) {
                    //do something else
                }
            });
    });
    </script>
      </body>
    </html>

这是你的test_Reg.php文件:

echo '<script type="text/javascript">
      whatIWant = {fruit: "apple",
      car: "Lotus",
      age: 31,
      hobby: "coding"};
      </script>';

也许您可以尝试将JSON存储为会话变量或cookie,然后用Javascript检索它。