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

标签 javascript php jquery ajax long-polling

我有以下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 进行硬编码(模拟外部表单发布的响应)并回显它时,它会出现在控制台中,但是 data 的条件.status==“成功”未得到检查。

这有什么问题吗?我错过了什么吗?

更新

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响应status200并且statusText“OK”错误 回调仍然被触发而不是 success

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

dataType: "json"

documentation声明 jQuery:

Evaluates the response as JSON and returns a JavaScript object. (...) The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.

这意味着,如果服务器返回无效 JSON 且状态为 200 OK,则 jQuery 会触发错误函数并将 textStatus 参数设置为“parsererror”。

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

<强>3。为什么ajax返回无效的JSON:

在您看来,在服务器端,您检查了 $_POST['status'] 以确保循环轮询中最后一次调用成功,仅 $_POST['status'] 设置后,您将回显 json,否则什么也不回显。

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

<强>4。解决方案:

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

$(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 });
        })();

    });

关于javascript - 使用 ajax 长轮询从外部 API 更新我的页面上的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37129486/

相关文章:

javascript - 当复选框名称来自php中的数据库时,如何访问多个复选框名称

php - 将自定义元数据插入数据库

jQuery UI 对话框(模态),防止任何回发

javascript - 检查元素是否有滚动-reactjs

javascript - 使用 javascript 为用户延迟加载内容的更好方法是什么?

javascript - 为什么 'arr.values()' 抛出错误 "arr.values is not a function"

javascript - JSON 在 js 中给出奇怪的格式化结果,我如何访问数据?

javascript - nvd3 "line plus bar chart"示例未显示

php - 保护 mp3 文件不被下载的有效方法是什么?

javascript - 通过 jQuery 从 div 获取数据到模态