ruby on rails return json to ajax

57 views
Skip to first unread message

fang

unread,
Aug 14, 2013, 2:53:47 AM8/14/13
to rubyonra...@googlegroups.com
how i  define my controller :
       def show
         @user=User.find(params[:id])
        respond_to do |format|
          format.json { render json: @user.to_json, :only => [:name, :email]}
        end
       end
how i define my ajax function:
  function FunAjax()
        {
            $.ajax({
                type: "POST",
                url: "http://ip:3000/users/1.json",
                data: "begin=1&end=9",
                dataType: "json",
                timeout : '50000',
                error : function(){
                    alert ('server error');
                },
                beforeSend: function(){
                    $("#span_content").text("processing...");
                },
                success:function(data){
                    if(data === null){
                        alert('no data');
                    }else{
                        var div_cont ="";
                        $.each(data,function(idx,arr_item){
                            div_cont = div_cont +"<br/>key:"+idx+"value:"+ arr_item;
                        }),
                        $("#span_content").html(div_cont);          
                    }
                     
                }
            });
        };
    $(document).ready(function () {
        alert('start');
    });

then i browse the url:http://ip:3000/users/1.json
it will return a string like this:
{"name":"fang","email":"fa...@fang.com"}
but the ajax function won`t work.
please tell me how can i exchange data between the server and the browser?

Hassan Schroeder

unread,
Aug 15, 2013, 4:01:03 PM8/15/13
to rubyonrails-talk
On Tue, Aug 13, 2013 at 11:53 PM, fang <gong...@gmail.com> wrote:

but the ajax function won`t work.

SMH. What does that mean? What's in your log? in your JavaScript 
console?

And why are you POSTing a request to a method that typically would
be accessed via GET, as in your browser (which apparently works)?
 
--
Hassan Schroeder ------------------------ hassan.s...@gmail.com
http://about.me/hassanschroeder
twitter: @hassan
Reply all
Reply to author
Forward
0 new messages