0

これが私がajaxリクエストを行う方法です

  #action
  def get_item
    if request.get?
      binding.pry  #it always stop here, so it's working
      item = Item.where(...)
      unless item
        item = Item.new
        # .....
      end
      respond_to do |format| 
        format.json { render(json: item) } 
      end
    elsif request.post?
       # ......
    end
  end

  #view
     $.ajax({
          type: "GET",
          url: "/contr/get_item",
                data: {key1: "value1"},
                //datatype: "json",
                success: function(data){
                  console.log("ajax success, data -> " + data[0]);
                    }
             });

内のコードget_itemは実行されdataますが、ページの値は常にundefinedです。

私は何を取りこぼしたか?

psリクエスト jsonでサーバーから送り返されていることに注意してください。F12をクリックして[ネットワーク]タブに移動すると、「デバッグツール」でChromeで表示できます。

4

2 に答える 2

1

これを試して:

 def get_item
   if request.get?
     item = Item.where(...)
     unless item
       item = Item.new
       # .....
     end
     render :json => item.to_json
   elsif request.post?
    #...
   end
 end

見る

   $.ajax({
      type: "GET",
      url: "/contr/get_item",
            data: {key1: "value1"},
            //datatype: "json",
            success: function(data){
              console.log("ajax success, data -> " + data[0]);
                }
         });
于 2013-01-27T04:31:35.830 に答える
0

URL には、使用する形式を指定する必要があります。あなたの場合.json、jsonで応答するために終了する必要があります。

#view
   $.ajax({
        type: "GET",
        url: "/contr/get_item.json",
于 2013-01-27T04:35:10.023 に答える