【问题标题】:Receive data from API and send it to another page via AJAX从 API 接收数据并通过 AJAX 将其发送到另一个页面
【发布时间】:2019-07-14 10:54:55
【问题描述】:

当我的工作区通过名为 asanatarget.php 的文件中的 POST 方法发生事件时,我正在从 API (asana) 接收数据

数据是正确的,我可以在收到时将其存储在文件中。 看起来像这样:

    {"events":"resource":xxx,"user":xxx,"type":"story","action":"added","created_at":"2019-02-20T14:48:09.142Z","parent":xxx}]}

在同一个文件中,我使用 GET 方法使用 AJAX 将数据发送到一个新文件:

asanatarget.php

<?php 
    if(isset($_SERVER['HTTP_X_HOOK_SECRET'])) {
        $h = $_SERVER['HTTP_X_HOOK_SECRET'];
        header('X-Hook-Secret:' . $h);
        exit;
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    </head>
    <body>
<?php
 $input = file_get_contents('php://input');

    if ($input) {
        $entries = json_decode(file_get_contents('php://input'), true);
        file_put_contents('targetasanaDATA' . time() . '.txt', json_encode($entries));
?>
    <script>
        $( document ).ready(function() {
            $.ajax({
                type: "GET",
                url: "/asanawebhook", // Working with laravel, the route is well defined
                data: <?php echo json_encode($entries); ?>,
                dataType: "json",

                success: function(response){ 
                    console.log("success " + response);
                },

                error: function(jqXHR, textStatus, errorThrown) {   // What to do if we fail
                    console.log(JSON.stringify(jqXHR));
                }

            });
        });  
    </script>


<?php 
} 

?>
</body>
</html>

当我直接用测试数据加载 asanatarget.php 时,它工作正常,数据被传递到 /asanawebhook 但是当数据直接从 api 传递时,它不起作用。 我检查了,数据总是正确的

【问题讨论】:

  • 如果你想通过请求发送数据,你应该使用 cURL POST。

标签: php jquery ajax api asana


【解决方案1】:

您的 PHP 脚本只生成一个 HTML 页面(基本上是一个文本)。

javascript 可以由浏览器解释和执行。但是如果没有浏览器读取这个页面并执行它,什么都不会发生。 PHP生成网页,没人看,事情到此结束。

您也可以使用 PHP 通过 POST 发送数据。您可以使用http_build_query() 构建查询并使用file_get_contents()

【讨论】:

    猜你喜欢
    • 2019-12-22
    • 2014-02-12
    • 1970-01-01
    • 2014-05-15
    • 2020-08-16
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2013-01-24
    相关资源
    最近更新 更多