jQuery对控制器操作的调用与预期不符 [英] jQuery call to controller action is not as expected

查看:97
本文介绍了jQuery对控制器操作的调用与预期不符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 jQuery :

var request = $.get("getPerforceSuites");
request.success(function(result){
    alert("res: " + result)
})
request.error(function(jqXHR, textStatus, errorThrown) {
    alert ("err: " + errorThrown);
})

以及 routes.rb 中的以下条目:

  get "getPerforceSuites", to: "perforce_sync#getPerforce"

和我的 perforce_sync_controller.rb :

  def getPerforce
    # return getRemoteSuites
    puts "++++++++++++++++++++++++++++++++++++++"
    puts "Called getPerforce"
    puts "++++++++++++++++++++++++++++++++++++++"
    return "Hi!"
  end

最初这没有用-直到我在/views/perforce_sync中创建了一个空的getPerforce.erb.html文件...现在,我可以肯定地说,肯定会调用getPerforce操作,因为出现了3条"puts"行在Rails服务器日志中.但是,我原以为"alert("res:" + result)会显示"Hi!" ...但是,我得到的是一堆HTML,看似是一个文档头(但是从哪个文件中,我'不知道!):

Initially this wasn't working - until I created an empty getPerforce.erb.html file in /views/perforce_sync... Now I can confidently say The getPerforce action is definitely being called, since the 3 "puts" lines appear in the rails server log. However, I had expected the "alert("res: " + result)" to show "Hi!"... But instead, I'm getting a whole heap of HTML, seemingly a document header (but from what file, I've no idea!):

res: <!DOCTYPE html>
<html>
<head>
  <title>Test1</title>
  <link data-turbolinks-track="true" href="/assets/application.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/authentication.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/bootstrap.css?body=1" media="all" rel="stylesheet" />  ***... SNIP ... ***

有人可以解释我在这里出了什么问题吗?我对jQuery有点陌生-但是没有经过大量的Google搜索就能使我认识到这个问题!

Can anyone explain what I'm getting wrong here? I'm kinda new to jQuery - but no amount of googling has resulted in my recognising the issue!

谢谢!

推荐答案

这是由于Rails响应控制器操作的方式所致.默认情况下,如果您未在控制器操作中调用render,则它将在您的views文件夹中查找模板.这就是为什么它要您创建getPerforce.erb.html文件的原因.

This is due to the way rails responds to controller actions. By default, if you don't call render in the controller action, then it will look in your views folder for a template. That's why it wanted you to create a getPerforce.erb.html file.

要使其仅返回纯文本,可以在控制器中编写:

To make it just return plain text, in the controller you can write:

render :text => 'Hi!'

如果您正在做AJAX东西,那么通常您将要返回JSON,您也可以像这样在控制器中完成

If you are doing AJAX stuff, then typically you will want to return JSON, you can also do this in the controller like so

render :json => {:data_key => 'A value'}

这篇关于jQuery对控制器操作的调用与预期不符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆