从Jquery中的选定列表元素中检索数据

时间:2013-02-16 00:37:42

标签: php jquery ajax json

我对整个编码工作都很陌生,并且最近在帮助下学到了很多东西,所以我希望它可以继续解决我遇到的下一个问题!

我有一个完美渲染的Jquery列表,它的作用是显示我输入的来自本地MYSQL数据库的虚拟信息。到目前为止,我所做的是,当用户点击其中一个列出的链接时,它会将它们带到下一页并说出“#34;您已选择链接#"此实例中的#标记表示用户选择列表链接的交易号。

我试图找出该做的是:

  1. 根据我从用户选择中获得的信息(即所选的商品编号),我怎样才能将其传回数据库,这样我就可以找到并检索带有该商号的特定条目。
  2. 我的HTML代码如下:

    <!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文件如下:

    <?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).'}';
    
    ?>
    

    我在这里不知所措,因为我一直在寻找有关此事的信息,似乎无法找到我正在寻找的东西。我感谢任何人的帮助,我的意思是!提前致谢!! :)

1 个答案:

答案 0 :(得分:0)

你可以像这样简化你的javascript:

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

如果要在不重新加载页面的情况下加载项目数据,则需要执行ajax请求。如果您不介意重新加载页面,请重定向到http://domain.com/uri/whatever?id=<the_selected_id>,然后在PHP脚本中,您可以使用get参数$_GET['id']获取项目,并执行查询以获取此ID的数据。

<强>更新

您需要一个PHP脚本来从数据库中检索数据。此脚本的调用方式如下:http://www.domain.com/foo/bar/my_script.php?id=<the_id_from_the_selection>

你的脚本应该是这样的:

<?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.

您的ajax请求(在用户选择内容时调用,这是javascript)应如下所示:

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
  }
});