php - 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,因为我已经创建了私有应用程序获取带有值的响应在此处输入图像描述
解决方案
您应该添加 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 参数中给出文件的完整可访问路径。
推荐阅读
- sql-server - 我有一个数据库 Probate。在这个数据库中,我想用 nvarchar、varchar 数据类型但 float 和 int 数据类型显示具有字符长度的数据类型
- reactjs - 在反应组件状态中存储字符串
- java - 如何在 Android 日记应用中显示条目并进行编辑
- post - 升级后最重要的帖子失败 - 请求正文中的帖子无效或缺失
- r - R:散点图上的“动画”点
- android - 电子邮件注册在片段内不起作用
- amazon-web-services - 从 AWS Aurora RDS 数据库备份快照还原(数据库实例)到现有数据库集群
- kubernetes - kubernetes - 入口网络策略未按预期工作
- linux - 重启linux后MongoDB服务终止
- qt - QML SplitView - 手动调整孩子的大小