简体   繁体   English

ajax请求服务器端脚本(控制器)获取服务器状态

[英]ajax request to the server side script (controller) to get the status of the server

I want to get a server side response for a button in a twig page.我想获得树枝页面中按钮的服务器端响应。 As a example - there will be 2 button in the page ---例如 - 页面中将有 2 个按钮 ---

ON/OFF开关

When the page load it should check from server (check from elasticsearch database) whether it returns True or false, for both button.当页面加载时,它应该从服务器检查(从 Elasticsearch 数据库检查)是否返回 True 或 false,对于两个按钮。

So for instanse we say that for ON button it return "True" it should change it color to green, like ----因此,例如我们说对于 ON 按钮它返回“True”它应该将其颜色更改为绿色,例如----

$(this).addClass('btn-success');
$(this).removeClass('btn-primary');

The main purpose is to check what's the current status, when the page load.主要目的是检查页面加载时的当前状态。

So this is not a on-click function, because it show show the status when the page is loaded.所以这不是点击功能,因为它显示页面加载时的状态。

This is my client side code ---这是我的客户端代码---

$(document).ready(function(){
   //send the request with empty data to the server to check the status
   $.post('/url/to/action', {}, function(msg){
     // we return a response like {status: 'on'} to the client if the search is on
     if (msg.status == 'on'){
       $('#my-button').addClass('success');
     }
     // else it is disabled
     else
       $('#my-button').addClass('primary');
   });
});

this is the integration with my symfony application ---这是与我的 symfony 应用程序的集成 ---

public function getStatusAction(Request $request){
    if ($output = !null) {
        return new \Symfony\Component\HttpFoundation\JsonResponse(array('status' => 'on'));
    } else {
        return new \Symfony\Component\HttpFoundation\JsonResponse(array('status' => 'off'));
    }
}

这是我跑去获取状态时的状态

This is the status when i run to get the status这是我跑去获取状态时的状态

Now the problem is when the page is loading it is not rerurning the status for the button.现在的问题是当页面加载时它没有重新显示按钮的状态。 I mean if the "status == 'on'" the button should be green instead of primary.我的意思是如果“状态 == 'on'”按钮应该是绿色而不是主要的。

Do anyone knows how i can fix this problem.有谁知道我如何解决这个问题。

to make that, you can use setInterval要做到这一点,您可以使用setInterval

function refreshStatus () {
    $.post('/url/to/action', {}, function (msg) {
        // we return a response like {status: 'on'} to the client if the search is on
        if (msg.status == 'on'){
            $('#my-button').addClass('success');
        }
        // else it is disabled
        else
            $('#my-button').addClass('primary');
    });
}

refreshStatus(); // call on page load
setInterval(refreshStatus, 5000); // call refreshStatus every 5 seconds

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM