2014-03-28 110 views
0

我有這樣的Ajax代碼檢索的JSON值

$(document).ready(function() { 
     for(var i=0;i<8;i++){ 
     $(".exac").append("<div class='ex' id='eas"+i+"' style='cursor:pointer'><h1 id='h1'></h1></div>"); 
     } 
     $('.ex').click(function() 
     { 
      var x=$(this).prop("id"); 
      $.ajax({ 
       type: "POST", 
       contentType: "application/json", 
       dataType: "json", 
       url: "/random/random", 
       success: function(msg){  
      alert(msg); 
          if(msg==01101){ 
          //$('.ex').attr('disabled','disabled'); 
          $(".ex").off('click'); 
          $("#hello").append("<button><a href='reset.jsp'>Reset</a></button>"); 
         } 
         else{ 
        $('<p>'+msg+'</p>').appendTo("#"+x); 
        $("#"+x).off('click'); 
        } 
       } 
      }); 
     }); 
     $('#button').removeAttr('disabled'); 
    }); 

,這是我CONTROLER

class RandomController < ApplicationController 

def random 
@n = 8 
    respond_to do |format| 
     #format.json { render :json => index } 
     format.json{render :json => ActiveSupport::JSON.encode(@n)} 
     format.html { redirect_to action: "index" } 

    end 
end 

end 

我使用AJAX選項進入控制器還我重定向回到索引頁面,但我不能在索引頁面收到@n=8的值。我錯過了一些步驟?

這是我在控制檯

enter image description here

回答

0

回答我上面的問題 我看來

$.ajax({ url: 'random', 
    type: 'POST', 
    beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, 
    data: {user:name}, 
    success: function(response) { 
    var foo = $.parseJSON(response); 
    if(foo==1001){ 
     alert("You can select only once"); 
    } 
    else{ 
     $('<p>'+foo+'</p>').appendTo("#"+x); 
     $("#"+x).off('click'); 
    } 
    } 
}); 

在控制器 我只是送這樣

render :text => @r.to_json 
0

得到錯誤,我不熟悉Ruby和Rails。然而; console.log(msg)而不是alert(msg),你會看到你的數據結構,然後你可以讀取msg.content數據。

我希望這有助於!

+0

日Thnx的反應,但我沒有得到紐約州的短信.. –