首页 > 解决方案 > API Response不为空时如何触发ajax?

问题描述

我正在使用 Shopify 客户/创建 webhook 并使用获取 API 响应

$info = file_get_contents('php://input');
$data = json_decode($info, true);

我想在 $data 不为空时触发 ajax

$.ajax({
    type: "POST",
    url: "insert.php",
    data: {
        'first_name'    : FirstName,
        'last_name'     : LastName,
        'email'         : Email,
        'password'      : Password,
    },
    success: function(res) {
        console.log("test");                      
    }
});

但它仅在我在 ngrok 检查中检查响应时显示值,如何在响应到来时触发此 ajax 请帮助文件扩展名为 .php,因为我已经创建了私有应用程序获取带有值的响应在此处输入图像描述

标签: phpajaxshopifyshopify-app

解决方案


您应该添加 if 条件并在就绪状态下运行 ajax 调用,我假设您已经在项目中加载了 jQuery。此外,您没有使用 ajax 函数处理错误回调,我已将它添加到您的函数中。

<?php
$info = file_get_contents('php://input');
$data = json_decode($info, true);

 if(!empty($data)){?>

 <script type="text/javascript">

    $( document ).ready(function() {

      $.ajax({
       type: "POST",
       url: "insert.php",
       dataType: "json",
       data: {
        first_name    : FirstName,
        last_name     : LastName,
        email         : Email,
        password      : Password,
       },
       success: function(res) {
          console.log("success");                      
        },
       error: function(res){
            console.log("error"); 
       }
     });// end of ajax

    });// end of ready
 </script>


 <?php
 }// end of if
 ?>

您应该更改 ajax 函数的参数中给出的 dataType,如果您在服务器文件中的响应是 JSON,则使用 dataType:“json”,但如果您从服务器文件返回 HTML,则使用 dataType:“html”。确保检查 ajax 文件的路径,在 url 参数中给出文件的完整可访问路径。


推荐阅读