【发布时间】:2016-09-04 21:33:06
【问题描述】:
我有以下 ajax 长轮询脚本
(function poll(){
$.ajax({ url: "<?php echo URL::to('/internal/v1/checkTxn'); ?>", success: function(data){
//Update your dashboard gauge
console.log(data.status); //Data is getting logged
if(data.status == 'success'){ //This condition is not being checked
console.log('suucesful'); //Not coming
}
}, dataType: "json", complete: poll, timeout: 1000 });
})();
后端PHP代码如下
if(isset($_POST['status']) && $_POST['status']){
$data = ['status'=>$_POST['status']];
$json = json_encode( $data );
echo $json;
}
流程
当我呈现页面时,ajax 脚本运行并等待响应。当我检查网络选项卡时,ajax 无休止地向指定的 URL 发出请求。
我从外部网站收到一个表单帖子到后端 PHP,我需要将其推送到 jquery。
但是,当发布帖子时,控制台中不会记录任何内容。但是如果我在 $json 中硬编码一些值并回显它,它就会出现在控制台中。
我面临两个问题
当一个帖子发生在 PHP 脚本上时,它不会出现在 ajax 代码中。
当我对 $json 进行硬编码(模拟外部表单发布的响应)并回显它时,它会出现在控制台中,但是 data 的条件.status== 'success' 没有得到检查。
这有什么问题。我错过了什么吗?
更新
I could fix the "condition not being checked" as there was something wrong the json being echoed. Now to avoid confusion, the flow for this User open the page, > The ajax starts the long polling process to my PHP code, waiting for a > response.User enters payment details in a form which is my html,clicks on pay, a pop up appears > which renders the banks login page (Payment gateway).After user entering all > details in the pop up (banks page), bank sents a server to server call about the status of > transaction to my notificationURL > ('mydomain.com/internal.v1/checkTxn'). As soon as I get a POST on this > URL(I will close the pop up), my ajax polling should get the data posted to my PHP and there by > I will show the status of TXN to the user on the same card form he entered his details earlier and > the pop window closes. The response here is returned by my PHP code to the ajax. The > post coming to my PHP code is a server to server post which is posted > by a Payment Gateway.
【问题讨论】:
-
你应该做 JSON.parse(data) 在成功时将它们转换为 ajax 中的 JS 对象,因为你在 JSON 中获取数据,我猜 (function(){...}(jQuery); 你必须将 jQuery 作为参数传递给 IIFE
-
从外部站点发布可能无法正常工作。 Ajax 通常仅限于同一个站点。
-
@Brett 不,expernal 站点发布到我的 PHP 脚本,然后 ajax 调用我服务器上的 php 脚本
标签: javascript php jquery ajax long-polling