Outputting jSON in a rails app

前端 未结 3 1554
我寻月下人不归
我寻月下人不归 2021-02-04 12:34

ok, rails 3 new developer here.

I want my jquery to be able to get a json object from the rails 3 application for projects. Here is my controller.

def yo         


        
3条回答
  •  臣服心动
    2021-02-04 13:28

    This is not issue of Rails but rather AJAX / jQuery not sending Accept header: Try this:

    $.ajax({
       url: 'url_to_action', dataType: "json",
         beforeSend : function(xhr){
           xhr.setRequestHeader("Accept", "application/json")
         },
         success : function(data){
           //.. do something with data
         },
         error: function(objAJAXRequest, strError, errorThrown){
           alert("ERROR: " + strError);
         }
      }
    );
    

    If all your AJAX requests expect JSON, then you can set header globally:

    $.ajaxSetup({
      dataType: 'json',
      'beforeSend' : function(xhr){
        xhr.setRequestHeader("Accept", "application/json")
      } 
    });
    

    Other option would be adding .json to path or data:{format: 'json'} to $.ajax hash of options. Rails supports format path suffixes by default for resoures routing. Just try rake routes to see.

提交回复
热议问题