2013-02-16 2 views
0

저는 코딩 작업에 익숙하지 않고 yer 도움말을 많이 배웠습니다. 다음 문제로 계속 진행되기를 바랍니다.Jquery에서 선택한 목록 요소의 데이터 검색

완벽하게 렌더링되는 Jquery 목록이 있는데 로컬 MYSQL 데이터베이스에서 입력 한 일부 더미 정보가 표시됩니다. 지금까지 내가 한 일은 사용자가 나열된 링크 중 하나를 클릭하면 다음 페이지로 이동하여 "귀하는 링크 #을 (를) 선택했습니다"라고 말하면이 인스턴스의 # 태그는 사용자의 거래 번호를 나타냅니다 선택된 목록 링크. 그때에이를 다시 전달하는 방법을 내가 (선택한 dealid 수 IE) 사용자 선택에서 얻은 한 정보와

  1. :

    은 내가 무엇을 찾아 노력하고있어 이것이다 데이터베이스 그래서 나는 그 dealid 번호와 특정 항목을 검색하고 검색 할 수 있습니다.

    다음과
    <!DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="utf-8" /> 
    <title>Find A Deal</title> 
    
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> 
    
        <style> 
         img.fullscreen { 
          max-height: 100%; 
          max-width: 100%; 
         } 
         </style> 
    
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> 
    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script> 
    <script type="text/javascript"> 
        $(document).on('pagebeforeshow', '#index', function(){ 
         $("#list").empty(); 
         var url="http://localhost/test/json3.php"; 
         $.getJSON(url,function(json){ 
          //loop through deals 
          $.each(json.deals,function(i,dat){ 
           $("#list").append("<li><a id='"+dat.dealid+"'><h1>"+dat.name+"</h1><p>"+dat.dname+"</p></a></li>"); 
           $(document).on('click', '#'+dat.dealid, function(event){ 
            if(event.handled !== true) // This will prevent event triggering more then once 
            { 
             listObject.itemID = $(this).attr('id'); 
             $.mobile.changePage("#index2", { transition: "slide"}); 
             event.handled = true; 
            } 
           });    
          }); 
          $("#list").listview('refresh'); 
         }); 
        }); 
    
        $(document).on('pagebeforeshow', '#index2', function(){  
        $('#index2 [data-role="content"]').html('You have selected Link' + listObject.itemID); 
    // var url="http://localhost/test/json9.php"; 
    // $.getJSON(url, function(json){ 
    
    
    
    
    
    
        }); 
    
        var listObject = { 
         itemID : null 
        }  
    </script> 
    </head>  
    <body>  
    <div data-role="page" id="index"> 
        <div data-role="header" data-position="fixed"> 
         <h1>Current Deals</h1> 
        </div> 
    
        <div data-role="content"> 
         <div class="content-primary"> 
          <ul id="list" data-role="listview" data-filter="true"></ul> 
         </div> 
        </div> 
    
        <div data-role="footer" data-position="fixed"> 
         <div data-role="navbar"> 
          <ul> 
           <li><a href="http://localhost/findadeal/index.html" data-icon="home">Home</a></li> 
           <li><a href="http://localhost/findadeal/mydeal.html" data-icon="grid">My Deals</a></li> 
          </ul> 
         </div> 
        </div> 
    </div> 
    
    <!--New Page --> 
    
    <div data-role="page" id="index2"> 
    <div data-role="header"> 
         <h1> Find A Deal </h1> 
        </div> 
    
        <div data-role="content"> 
         <a data-role="button" href="#page1" data-icon="star" data-iconpos="left">Get Deal </a> 
        </div> 
    
        <footer data-role="footer" data-position="fixed"> 
         <nav data-role="navbar"> 
          <ul> 
           <li><a href="index.html" data-icon="home">Home</a></li> 
           <li><a href="#index" data-icon="grid">My Deals</a></li> 
          </ul> 
         </nav> 
        </footer> 
    </div> 
    </body> 
    </html> 
    

    원래 목록 (Json3.php)을 만들 참조되고있는 PHP/JSON 파일이 될 때 : 다음과 같이

내 HTML 코드는

<?php 

$link = mysql_pconnect("localhost", "root", "") or die ("Could not Connect to DB"); 

mysql_select_db("findadeal") or die("Could not select database"); 

$arr = array(); 

$rs = mysql_query("SELECT r.restaurantid, r.name, r.image, d.dealid, d.dname, d.restaurantid 
FROM restaurant r, deal d 
WHERE r.restaurantid = d.restaurantid;"); 

while($obj = mysql_fetch_object($rs)) { 
$arr[] = $obj; 
} 

echo '{"deals":'.json_encode($arr).'}'; 

?> 

내가 잠시 동안 이것에 대한 정보를 찾고 있었고 내가 찾을 수있는 것을 찾지 못하는 것 같이 나는 여기서 잃어 버리고있다. 아무도 도와 주셔서 감사합니다. 정말 의미가 있습니다! 미리 감사드립니다 !! :)

답변

0

는이처럼 자바 스크립트를 단순화 할 수 있습니다 :

$(document).on('click', '#'+dat.dealid, function(event){ 
    listObject.itemID = $(this).attr('id'); 
    $.mobile.changePage("#index2", { transition: "slide"}); 
    event.stopPropagation(); 
}); 

페이지를 다시로드하지 않고 항목의 데이터를로드하려면

은 다음 아약스 요청을 할 필요가있다. 페이지를 다시로드하는 데 신경 쓰지 않는다면 http://domain.com/uri/whatever?id=<the_selected_id>으로 리디렉션 한 다음 PHP 스크립트에서 get 매개 변수 $_GET['id']을 사용하여 항목을 가져 와서 쿼리를 수행하여이 ID에 대한 데이터를 가져올 수 있습니다.

UPDATE 당신은 데이터베이스에서 데이터를 검색하기 위해 PHP 스크립트가 필요합니다. http://www.domain.com/foo/bar/my_script.php?id=<the_id_from_the_selection>

그리고 스크립트가해야는 다음과 같습니다 :이 스크립트는 다음과 같이 호출

var dealId; // the selected deal id 

$.ajax({ 
    url : 'foo/bar/my_script.php', 
    data: {id: dealId}, 
    type: "GET", 
    async: true, 
    onSuccess: function(response){ 
    console.log(response); // look into the console to check the object structure 
    // Display your data here using dom selector and jquery 
    } 
}); 
:

<?php 

// Default value to return 
$data = array('error' => 'No deal found'); 

if (isset($_GET['id']) && is_numeric($_GET['id'])) { 

    // Using PDO for the database connection, it's much better and avoid SQL injection 
    // Make sure the PDO extension is enable in your php.ini 
    $pdo = new \PDO('mysql:host=localhost;dbname=<SOMEDB>', '<USERNAME>', 'PASSWORD'); 

    $sql = "SELECT * FROM deal WHERE id = :id"; 
    $statement = $pdo->prepare($sql); 
    $statement->execute(array('id' => $_GET['id'])); 
    $data = $statement->fetch(\PDO:FETCH_ASSOC); 
} 

echo json_encode($data); 

// You don't need the closing PHP tag. Actually it's easier to debug if you don't use it. 

귀하의 아약스 요청과 같아야합니다 (사용자가 무언가를 선택할 때 호출이 자바 스크립트입니다)

+0

빠른 답장을 보내 주셔서 감사합니다. 좋게 들리 겠지만, 나는 그 (것)들을하는 방법을 계산하기 전에 그 (것)들의 2 개 방법에 관하여 읽는 조금을 첫째로 읽어야한다. 네가 제안한 두 번째 방법이 무엇인지 생각 해봐? 아니면 2 중 어느 것을 개인적으로 추천 하시겠습니까? 왜냐하면 나는 페이지를 새로 고치지 않아도 앱이 더 좋아 보이게 할 것이지만 업계 표준이 무엇인지 확신 할 수 없다고 생각한다. – user2025934

+0

같은 페이지에 데이터를 표시해야하는 경우 드롭 다운에서 아약스를 사용하는 것이 좋습니다. 그것을 위해 jQuery $ .ajax()를 권하고 싶습니다. 데이터베이스에서 데이터를 가져 와서 반환하려면 PHP 스크립트를 호출해야합니다 (json 문자열로 PHP'json_encode()'참조). $ .ajax() tutoriel을 찾으면 원하는 것을 찾을 수 있습니다. – maxwell2022

+0

Drop Down Select? 그게 일종의 목록인가요? 제가 사용하는 목록은 표준적인 것입니다. 사용자가 특정 페이지로 이동할 때 다른 요소가 전체 페이지에 나열됩니다. 그런 다음 선택이 이루어지면 새 정보를 표시하려는 새 페이지로 이동합니다. 그래도 그 $ .ajax를 계속 사용하고 있습니까? – user2025934

관련 문제