使用ajax长轮询从外部API更新页面上的响应

Using ajax long polling to update a response on my page from an external API

本文关键字:响应 更新 API ajax 从外部 使用      更新时间:2023-09-26

我有以下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;
        }

流量

  1. 当我呈现页面时,ajax脚本会运行并等待响应。当我检查网络选项卡时,ajax无休止地向指定的URL发出请求。

  2. 我收到了一个从外部网站到后端PHP的表单帖子,我需要将其推送到jquery。

但是,当一个帖子发生时,控制台中不会记录任何内容。但是,如果我在$json中硬编码一些值并回显它,它就会出现在控制台中。

我面临两个问题

  1. 当一个帖子出现在PHP脚本上时,它不会出现在ajax代码中。

  2. 当我硬编码(模拟外部表单帖子发布的响应)$json并回显它时,它会出现在控制台中,但没有检查数据的条件。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.

1。让我们调试一下:

设置ajax错误回调,

$(function(){
        (function poll(){
            $.ajax({ url: "http://tinyissue.localhost.com/test.php", 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
                }
            },error:function(err){
                console.info('error fired...');
                console.info(err);
            }, dataType: "json", complete: poll, timeout: 1000 });
        })();
    });

运行这个,你会得到控制台

error fired...
Object {readyState: 4, responseText: "", status: 200, statusText: "OK"}

2.为什么进行错误回调:

为什么ajax响应status200statusText"OK"时,error回调仍被触发而不是success

您的AJAX请求包含以下设置:

dataType: "json"

文档指出jQuery:

将响应求值为JSON并返回一个JavaScript对象。(…)JSON数据以严格的方式进行解析;任何格式错误的JSON都是被拒绝,并引发解析错误。

这意味着,如果服务器返回无效的JSON,状态为200 OK时,jQuery将触发错误函数并将textStatus参数设置为"parserror"。

解决方案:确保服务器返回有效的JSON。值得注意的是,空响应也被认为是无效的JSON;例如,您可以返回{}或null,以JSON形式进行验证。

3.ajax返回无效JSON:的原因

在您的脑海中,在服务器端,您检查了$_POST['status']以确保循环轮询中的最后一次调用成功,只设置了$_POST['status'],您将回显json,或者不回显任何内容。

但是,不幸的是,在调用循环开始时,ajax第一次调用时,您没有将status设置为post。然后它什么也不回,然后它去了error回调,也去了complete回调,然后在没有status发布的情况下再次调用。看,这是一个糟糕的循环。

4.解决方案:

status值设置为在第一次ajax调用时发布。

$(function(){
        (function poll(){
            var status = 'success';
            $.ajax({ url: "http://tinyissue.localhost.com/test.php", success: function(data){
                //Update your dashboard gauge
                console.log(data.status);  //Data is getting logged
                status = data.status;
                if(data.status == 'success'){  //This condition is not being checked
                    console.log('suucesful'); //Not coming
                }
            },error:function(err){
                console.info('error fired...');
                console.info(err);
                status = 'error';
            }, type:'post',dataType: "json", data:{status:status}, complete: poll, timeout: 1000 });
        })();
    });

如果使用长轮询,则可能存在缓存问题。首先,当你的帖子进入你的系统时,检查checkTxn是否发生了变化。最后,你可以在url查询中添加一个随机参数(例如,通过添加以毫秒为单位的日期),你不会使用它,但你的服务器会认为你的请求不同。

请检查一下,让我们知道。

@编辑:当然@Ajeesh,我来解释一下:

(function poll(){
    $.ajax({ url: "<?php echo URL::to('/internal/v1/checkTxn');  ?>?_ts=" + new Date().getTime(), 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 });
})();

这样做,缓存将不会被使用,因为对于您的服务器/浏览器,所有查询都是不同的。

另一方面,我要求您在收到POST时对页面进行任何更改,因此,如果没有,您的ajax将永远不会收到通知,您知道我的意思吗?