简体   繁体   English

Rails控制器未收到Ajax呼叫

[英]Ajax call not received by rails controller

my Ajax call via jQuery will always be transmitted (status 200), but only sometimes it's received by the rails controller. 我通过jQuery进行的Ajax调用将始终被传输(状态200),但仅在某些情况下会被rails控制器接收。 Means the data is sent properly but most times the controller sends back an empty json object as the response. 表示数据已正确发送,但大多数情况下,控制器会发回一个空的json对象作为响应。 I need the timeout else the stringify doesn't work. 我需要超时,否则stringify无法正常工作。 Any hints? 有什么提示吗?

setTimeout(function() {
      $.ajax({
        type: "POST",
        url: "homepage/routes",
        data: {
          routes_my: JSON.stringify(routes)
        },
        success: function(data) {
          console.log(data);
        }
      });
    }, 100);
  }

#Controller
      def routes
        @routes = JSON.parse(params\[:routes_my\], object_class: OpenStruct)
        render :json => @routes
      end

console log working example 控制台日志工作示例

console log bad example 控制台日志错误示例

Try this function. 试试这个功能。

$(document).ready(function(){
    var obj = JSON.stringify(routes);
    $.ajax({
            type: "POST",
            url: "homepage/routes",
            data: {routes_my: obj},
            success: function(data) {
              console.log(data);
            }
          });
});

Actually the problem was that "routes" is the result of an async function and was sometimes only partially available. 实际上,问题在于“路由”是异步功能的结果,有时仅部分可用。 Fixed that by calling the Ajax as a callback function. 通过调用Ajax作为回调函数来解决此问题。 setTimeout is then irrelevant. setTimeout则无关紧要。

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

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