简体   繁体   中英

AJAX Jquery in rails

I am trying to pass data from view to Controller, but data not passing so what is wrong in my app ?

in view:

var url = 'searchs/index';

$( "#h" ).click(function() {

  $.ajax({ type: "GET", url: url, data: {xx: 'q'} }); 

});

Controller:

class SearchsController < ApplicationController

def index

@x=User.new(:name=> params[:xx])

@x.save

end

end

You should first follow the convention of Rails RESTful routing and use the index endpoint as a way to list all "searchs." I don't get why you are doing UsersController#create stuff in SearchsController#index .

Anyway, once you straighten that out, let's say you have some controller endpoint called SearchsController#custom (you shouldn't call it that, but I cant think of anything better) that you map to searchs_custom_path .

Then do something like this in your template:

<%= hidden_field_tag "searchsCustomPath", searchs_custom_path %>

Then in your JavaScript do this:

$( "#h" ).click(function() {    
   $.ajax({
       type: "GET",
       url: $("#searchsCustomPath").val(),
       data: {xx: 'q'}
   });
});

This way you don't hardcode the URL and violate DRY while still making the right Rails-generated URL available to JQuery.

Replace this

var url = 'searchs/index';

With this

var url = '<%= searchs_path %>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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