AJAX请求后向rails控制器发送数据会得到404

时间:2022-10-07 14:26:59

I want to post data to a rails controller via an AJAX request

我想通过AJAX请求将数据发布到rails控制器

My route: get "pki_login/authenticate" => "pki_logins#authenticate"

我的路径:获取“pki_login/authenticate”=>“pki_logins#authenticate”

The JS:

JS:

$.ajax({
    type: 'POST',
    url: '/pki_login/authenticate',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        alert("Successful");
      },
    data: passcode
});

then inside pki_logins_controller.rb i have:

然后在pki_logins_controller。rb我有:

def authenticate
  puts params[:passcode]
end

the authenticate.html.erb file just contains a h3 tag.

authenticate.html。erb文件只包含一个h3标签。

I can visit /pki_login/authenticate and it works, but when accessing via AJAX I get a 404 so I don't even know if the POST works either

我可以访问/pki_login/authenticate,它是有效的,但是当我通过AJAX访问时,我得到的是404,所以我甚至不知道这篇文章是否有效

1 个解决方案

#1


6  

You're defining a get route but making POST request.

您定义了一个get路由,但是发出POST请求。

Try:

试一试:

$.ajax({
    type: 'GET',
    url: '/pki_login/authenticate',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        alert("Successful");
      },
    data: passcode
});

Or change the route to post and use post ajax request as:

或更改发送和使用post ajax请求的路由:

# config/routes.rb
post "pki_login/authenticate" => "pki_logins#authenticate"

Then the ajax call:

然后ajax调用:

$.ajax({
    type: 'POST',
    url: '/pki_login/authenticate',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        alert("Successful");
      },
    data: passcode
});

#1


6  

You're defining a get route but making POST request.

您定义了一个get路由,但是发出POST请求。

Try:

试一试:

$.ajax({
    type: 'GET',
    url: '/pki_login/authenticate',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        alert("Successful");
      },
    data: passcode
});

Or change the route to post and use post ajax request as:

或更改发送和使用post ajax请求的路由:

# config/routes.rb
post "pki_login/authenticate" => "pki_logins#authenticate"

Then the ajax call:

然后ajax调用:

$.ajax({
    type: 'POST',
    url: '/pki_login/authenticate',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        alert("Successful");
      },
    data: passcode
});