1

나는 간단한 레일 앱을 통해 항목 목록을 표시하고 jquery mobile을 사용하여 기본 모바일 응용 프로그램을 만들고 해당 항목이 기본 사이트에서 제공 될 것입니다. 내 컨트롤러는jquery mobile 및 json in Rails 사용

class ListsController < ApplicationController 

    respond_to :json 

    def index 
    @lists = List.all 
    respond_with(@lists) 
    end 

    # ... 
end 

다음 내 네이티브 모바일 앱에서 내 index.html 페이지에서 이것을 가지고있다

$.ajax({ 
    url: "http://localhost:3000/lists", 
    dataType: "json", 
    type: "GET", 
    processData: false, 
    contentType: "application/json" 
}); 

이 데이터를 가져올이고 내가 그것을 JQuery와 모바일 템플릿에 추가 할 싶습니다 li 탭 안쪽. 어떻게 jquery를 사용하여이 작업을 수행 할 수 있습니다.

$.ajax({ 
    url: "http://localhost:3000/lists", 
    dataType: "json", 
    type: "GET", 
    processData: false, 
    contentType: "application/json", 
    success: function(transport){ 
    insertMyStuff(transport); 
    } 
}); 

내가 밖으로 콜백의 논리를 이동하고자 :

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Page Title</title> 

    <meta name="viewport" content="width=device-width, initial-scale=1"> 

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" /> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script> 
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script> 
</head> 

<body> 
<div data-role="page"> 
    <div data-role="header"> 
      <h1>Simple test app</h1> 
     </div> 
    <div data-role="content"> 
     <ul> 
      <li>(content appends here)</li> 
     </ul> 
     </div> 
    <div data-role="footer"> 
      <h4>test app</h4> 
     </div> 
</div> 
</body> 
</html> 

json으로 출력 예는

json output

+1

무엇 JSON 출력은 좋아? 예제를 게시 할 수 있습니까? – Jasper

+0

그냥 uopated – Uchenna

+0

내 대답은 JSON 출력을 반영하도록 업데이트되었습니다. 'serverResponse [0] .list.title'는 첫 번째 제목을 출력하고'serverResponse [1] .list.title'는 두 번째 제목을 출력합니다. 내 예제에서는 모든 반환 된 객체를 반복하는 방법을 보여줍니다. – Jasper

답변

0

당신이 DOM에 대한 서버 응답을 추가 할 수있는 success 콜백 기능을 설정할 수 있습니다 전화 : 당신이 ID를 추가하거나해야

$.ajax({ 
    url   : "http://localhost:3000/lists", 
    dataType : "json", 
    type  : "GET", 
    processData : false, 
    contentType : "application/json", 
    success  : function (serverResponse) { 

     //setup an output variable to buffer the output 
     var output = []; 

     //since you aren't telling the `.ajax()` function to parse your response you need to do it here so the string returned from the server is an object 
     serverResponse = $.parseJSON(serverResponse); 

     //iterate through the results, assuming the JSON returned is an array of objects 
     for (var i = 0, len = serverResponse.length; i < len; i++) { 
      output[output.length] = '<a href="#' + serverResponse[i].list.id + '">' + serverResponse[i].list.title + '</a><br />'; 
     } 

     //now append all the output at once (this saves us CPU cycles over appending each item separately) 
     $('[data-role="content]').children('ul').children('li').eq(0).html(output.join('')); 
    } 
}); 

을 여기에 간단한 방법입니다 클래스를 HTML 마크 업의 일부 요소에 추가하면 원하는 LI 만 찾을 수 있습니다. data-role="page"에게 ID를 부여하면 을 타겟팅 할 수 있습니다.

$ ('# page-id'). children ('[data-role = "page"]'). 어린이 ('ul '). 어린이 ('li '). eq (0);

에는 UL 요소에 복수 LIs이 있습니다.

+0

방금 ​​질문을 업데이 트 – Uchenna

+0

당신은 오신 것을 환영합니다. – Jasper

0

아래 첫 번째입니다 감사합니다, 당신은 아약스에게 콜백을 제공해야 아약스 블록 :

insertMyStuff = function(transport){ 
    $("#my_li_id").append(transport); 
    //or iterate over your json however you like here 
} 

<li>에 jquery의 ID를 지정해야 해당 접근법을 찾을 수 있습니다. 당신의 AJAX에서

<li id="my_li_id">(content appends here)</li> 
+0

하나가 아닌 두 가지 기능을 만드는 이유는 무엇입니까? 'insert'' 콜백 함수에 직접'insertMyStuff' 코드를 넣을 수는 없습니까?또한 JSON이 반환되면 DOM에 추가하지 않고 JSON 객체를 반복하여 원하는 정보 만 DOM에 추가 할 수 있습니다. – Jasper

+0

하나면 충분합니다. 나는 콜백 논리를 다른 함수로 옮겨서 아약스 블록을보다 간결하게 유지하는 습관에있다. –

+0

아주 좋다. 물마루 가겠다 – Uchenna