当前位置: 首页 > 面试题库 >

jQuery Mobile:将数据从一页发送到另一页

司寇高峯
2023-03-14
问题内容

我有问题,我需要将数据(ID)从列表发送到另一页。这是html代码:

</head>
    <body>
        <div data-role="page" id="index">
            <div data-role="header">
                <h1>Players App</h1>
            </div><!--/header-->
            <div data-role="content">
                <ul data-role="listview" id="ul_list" data-inset="true">

                </ul>
            </div><!--/content-->
            <div data-role="footer">
                <h4>Players list</h4>
            </div><!--/footer-->
        </div><!--/page-index-->
        <div data-role="page" id="detail" data-add-back-btn="true">
            <div data-role="header">
                <h1>Player detail</h1>
            </div><!--/header-->
            <div data-role="content">
                <ul data-role="listview" id = "" data-inset="true">

                </ul>
            </div><!--/content-->
            <div data-role="footer">
                <h4>Players list</h4>
            </div><!--/footer-->
        </div><!--/page-detail-->
    </body>
</html>

这是脚本:

var lista = new Array();
var squadraManager={};

squadraManager.initArray=null;
squadraManager.printArray=null;

squadraManager.initArray = function(){
        lista[0] = new players();
        lista[0].setNome("Nonho");
        lista[0].setRuolo("difensore");
        lista[0].setCognome("Rossi");
        lista[0].setNMaglia("01");
        lista[1] = new players();
        lista[1].setNome("Marco");
        lista[1].setRuolo("blabla");
        lista[1].setCognome("Mariani");
        lista[1].setNMaglia("22");
        lista[2] = new players();
        lista[2].setNome("Carlo");
        lista[2].setRuolo("Soffiatore");
        lista[2].setCognome("Bianchi");
        lista[2].setNMaglia("01");
}
squadraManager.loaderList = function(){
    jQuery.each( lista, function(chiave, oggetto){
        //leggo valori oggetti in array 
            jQuery("#ul_list").append("<li><a id='"+ oggetto.getId() +"det' href='#dettaglio'>"+oggetto.getCognome()+"</a></li>").listview("refresh");
    });
}


squadraManager.init = function(){                             /*init */
    squadraManager.initArray();
    squadraManager.loaderList();
}
jQuery(function(){
    squadraManager.init();
});

我希望将单击列表的ID发送到下一页。最终的想法是在第二页“ #detail”中加载播放器的详细信息(播放器位于单独的类中)。

感谢您的回复


问题答案:

一个HTML /多页模板

这是在1个html多页模板中将属性从listview传递到第二页的示例:

http://jsfiddle.net/Gajotres/Gv7UW/-js对象作为存储容器

http://jsfiddle.net/Gajotres/J9NTr/-localStorage作为存储容器

基本上,您要做的是创建一个持久性javascript对象以用于存储。只要使用ajax进行页面加载(并且不会以任何方式重新加载页面),该对象就会保持活动状态。

    var storeObject = {
        firstname : '',
        lastname : ''
    }

多个HTML页面模板

不幸的是,此示例无法通过jsFiddle完成,因此我将发布所需的文件:

HTML 1:

<!DOCTYPE html>
<html>
<head>
    <title>jQM Complex Demo</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
    <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.8.3.min.js"></script>    
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>  
    <script src="operations.js"></script>       
</head>
<body>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3>
                First Page
            </h3>
            <a href="#second" class="ui-btn-right">Next</a>
        </div>

        <div data-role="content">
            <ul data-role="listview" data-theme="a" id="test-listview">
                <li><a href="page2.html?id=1">Link 1</a></li>
                <li><a href="page2.html?id=2">Link 2</a></li>
                <li><a href="page2.html?id=3">Link 3</a></li>
                <li><a href="page2.html?id=4">Link 4</a></li>
                <li><a href="page2.html?id=5">Link 5</a></li>
            </ul>    
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>    
</body>
</html>

HTML 2:

<!DOCTYPE html>
<html>
<head>
    <title>jQM Complex Demo</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
    <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.8.3.min.js"></script>    
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>  
</head>
<body>
    <div data-role="page" id="second">
        <div data-theme="a" data-role="header">
            <h3>
                Second Page
            </h3>
            <a href="#index" class="ui-btn-left">Back</a>
        </div>

        <div data-role="content">

        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>    
</body>
</html>

Operations.js:

$(document).on('pageshow', '#second', function(){   
    alert(getParameterByName("id"));
});


function getParameterByName(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

用户认证演示

另一个无法用jsFiddle示例显示的示例,与前面的示例不同,该示例将附加SQL脚本。我建议您创建一个更好的数据库读取逻辑,这是一个简单的解决方案,易于进行SQL注入,但对于您的分配来说效果很好:

index.php:

<!DOCTYPE html>
<html>
<head>
    <title>jQM Complex Demo</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
    <style>
        #login-button {
            margin-top: 30px;
        }        
    </style>
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>    
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
    <script src="js/custom.js"></script>
</head>
<body>
    <div data-role="page" id="login">
        <div data-theme="a" data-role="header">
            <h3>Login Page</h3>
        </div>

        <div data-role="content">
            <label for="username">Enter your username:</label>
            <input type="text" value="" name="username" id="username"/>
            <label for="password">Enter your password:</label>
            <input type="password" value="" name="password" id="password"/>  
            <a data-role="button" id="login-button" data-theme="b">Login</a>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3></h3>
        </div>

        <div data-role="content">
            Here goes content
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">
            <h3>Page footer</h3>
        </div>
    </div>    
</body>
</html>

json.php:

<?php
    $var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
    $jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object

    $username = $jsonObject->{'username'}; // Get username from object
    $password = $jsonObject->{'password'}; // Get password from object

    mysql_connect("localhost","root","");  // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
    @mysql_select_db("test") or die( "Unable to select database"); // Connect to database called test

    $query = "SELECT * FROM users WHERE user_name = '".$username."' and user_pass = '".$password."'";
    $result=mysql_query($query);
    $num = mysql_numrows($result);

    if($num != 0) {
        echo "true";
    } else {
        echo "false";        
    }
?>

custom.js:

$(document).on('pagebeforeshow', '#login', function(){ 
    $('#login-button').on('click', function(){
        if($('#username').val().length > 0 && $('#password').val().length > 0){
            userObject.username = $('#username').val(); // Put username into the object
            userObject.password = $('#password').val(); // Put password into the object
            // Convert an userObject to a JSON string representation
            var outputJSON = JSON.stringify(userObject);
            // Send data to server through ajax call
            // action is functionality we want to call and outputJSON is our data
            ajax.sendRequest({action : 'login', outputJSON : outputJSON});
        } else {
            alert('Please fill all nececery fields');
        }
    });    
});

$(document).on('pagebeforeshow', '#index', function(){ 
    if(userObject.username.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
        $.mobile.changePage( "#login", { transition: "slide"} ); // In case result is true change page to Index  
    }
    $(this).find('[data-role="header"] h3').append('Wellcome ' + userObject.username); // Change header with wellcome msg
    //$("#index").trigger('pagecreate');
});

// This will be an ajax function set
var ajax = {
    sendRequest:function(save_data){
        $.ajax({url: 'http://localhost/JSONP_Tutorial/json.php',
            data: save_data,
            async: true,
            beforeSend: function() {
                // This callback function will trigger before data is sent
                $.mobile.showPageLoadingMsg(true); // This will show ajax spinner
            },
            complete: function() {
                // This callback function will trigger on data sent/received complete
                $.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
            },
            success: function (result) {
                if(result == "true") {
                    $.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
                } else {
                    alert('Login unsuccessful, please try again!'); // In case result is false throw an error
                }
                // This callback function will trigger on successful action
            },
            error: function (request,error) {
                // This callback function will trigger on unsuccessful action                
                alert('Network error has occurred please try again!');
            }
        });
    }
}

// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
    username : "",
    password : ""
}

本地主机.sql

-- phpMyAdmin SQL Dump
-- version 3.4.10.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Feb 02, 2013 at 11:58 AM
-- Server version: 5.5.20
-- PHP Version: 5.3.10

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `test`
--
CREATE DATABASE `test` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `test`;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(64) NOT NULL,
  `user_pass` varchar(64) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`user_id`, `user_name`, `user_pass`) VALUES
(1, 'gajotres', 'testpass');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

更多信息

如果您想了解有关此主题的更多信息,请阅读本文。您将找到带有示例的几种解决方案。



 类似资料:
  • 你好,我想把数据从一个html页面发送到另一个html页面 这是我的index.html页面 这是newpage.html:

  • 我目前正在做一个项目,我需要帮助。 我想发送的名称,总数量和总价的一个产品的数量在我的添加到购物车活动。 @override public void onListClick(final ItemInfo item){ 上面应该有什么代码发送到购物车活动?? toast.maketext(mainactivity.this,“added To cart”,toast.length_short).sh

  • 我有一个来自firebase的uid,但它是这样存储的: checkout.js 存储我需要传递到另一个页面的uid。这个uid存储在中,我需要将它放到中才能在那里使用uid。我该怎么做?如果需要更多代码,请让我知道。我正在使用react/js

  • 我需要将数据从片段发送到另一个活动 我在Homeactive下的LoadsFraank中使用此代码 在另一个活动(LoadActivity)中接收数据 但是意图没有附加条件 请看下面的截图

  • 问题内容: 我有一个JSP文件为 jsp 1.jsp ,另一个JSP文件为 jsp 2.jsp 我已经包括 JSP 2.jsp 在 JSP 1.jsp页面 使用 现在,我需要某些元素上的click事件。在那件事上,我想将一个字符串变量传递给包含的jsp。 假设我有一个列表,单击它后,我想将该列表的名称转移到另一个JSP, 在另一个JSP中,我试图使用该字符串执行某些任务。 我在没有任何servle

  • 我很难在Thymeleaf帖子中绑定一个ObjectList。 我正在尝试使用Spring5和ThymeLeaf来实现以下要求 我计划在每行添加一个删除按钮。和一个Submit按钮,用于将所有剩余行保存在DB中。 如何将eachRowList转发到另一个控制器(用于删除操作和数据库保存)。 更新1: 修改视图 最终更新: 显然th:field输入标签不会绑定在thead部分(它不应该有输入字段Lo