jQuery Mobile:如何正确地提交表单数据 [英] jQuery Mobile: How to correctly submit form data

查看:125
本文介绍了jQuery Mobile:如何正确地提交表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个jQuery Mobile问题,但它也涉及纯jQuery。



如何将表单数据无页面转换到页面设置为form action属性。我正在构建phonegap应用程序,我不想直接访问服务器端页面。



我尝试了几个例子,但每次表单转发我到目的地PHP文件。

解决方案

简介



此示例是使用jQuery Mobile 1.2创建的。如果您想查看最近的示例,请查看此 文章 或此更复杂 一个 。你会发现2个工作实例详细解释。



表单提交是一个常见的jQuery Mobile问题。



<有几种方法可以实现。



示例1:



这是最好的解决方案,使用phonegap应用程序,你不想直接访问服务器端php。这是一个正确的解决方案,如果你想创建一个phonegap iOS应用程序。



index.html

 <!DOCTYPE html> 
< html>
< head>
< title> jQM复杂演示< / title>
< meta name =viewportcontent =width = device-width,height = device-height,initial-scale = 1.0/>
< link rel =stylesheethref =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 / index.js>< / script>
< / head>
< body>
< div data-role =pageid =logindata-theme =b>
< div data-role =headerdata-theme =a>
< h3>登录页面< / h3>
< / div>

< div data-role =content>
< form id =check-userclass =ui-body ui-body-a ui-corner-alldata-ajax =false>
< fieldset>
< div data-role =fieldcontain>
< label for =username>输入您的用户名:< / label>
< input type =textvalue =name =usernameid =username/>
< / div>
< div data-role =fieldcontain>
< label for =password>输入您的密码:< / label>
< input type =passwordvalue =name =passwordid =password/>
< / div>
< input type =buttondata-theme =bname =submitid =submitvalue =Submit>
< / fieldset>
< / form>
< / div>

< div data-theme =adata-role =footerdata-position =fixed>

< / div>
< / div>
< div data-role =pageid =second>
< div data-theme =adata-role =header>
< h3>< / h3>
< / div>

< div data-role =content>

< / div>

< div data-theme =adata-role =footerdata-position =fixed>
< h3>页脚< / h3>
< / div>
< / div>
< / body>
< / html>

check.php:

 <?php 
// $ action = $ _REQUEST ['action']; //我们不需要为这个教程的行动,但在一个复杂的代码,你需要一种方法来确定ajax动作自然
// $ formData = json_decode($ _ REQUEST ['formData']); //将JSON对象解码为可读的PHP对象

// $ username = $ formData-> {'username'}; //从对象获取用户名
// $ password = $ formData-> {'password'}; //从对象获取密码

//让我们说一切顺序
echoUsername =;
?>

index.js

  $(document).on('pagebeforeshow','#login',function(){
$(document).on #submit',function(){//捕捉表单的提交事件
if($('#username')。val()。length> 0&& $('#password')。val ().length> 0){
//通过ajax调用发送数据到服务器
// action是我们想要调用的函数,outputJSON是我们的数据
$ .ajax({url :'check.php',
data:{action:'login',formData:$('#check-user')。serialize()},//将表单转换为JSON字符串表示
type:'post',
async:true,
beforeSend:function(){
//这个回调函数会在数据发送前触发
$ .mobile.showPageLoadingMsg true); //这将显示ajax微调
},
complete:function(){
//这个回调函数将触发数据发送/接收完成
$ .mobile .hidePageLoadingMsg(); //这将隐藏ajax微调框
},
success:function(result){
resultObject.formSubmitionResult = result;
$ .mobile.changePage(#second);
},
错误:function(request,error){
//这个回调函数将触发不成功的操作
alert('发生网络错误,请重试! ;
}
});
} else {
alert('Please fill all nececery fields');
}
return false; // cancel original event to prevent form submittedting
});
});

$(document).on('pagebeforeshow','#second',function(){
$('#second [data-role =content]')。 ('这是表单提交的结果:'+ resultObject.formSubmitionResult);
});

var resultObject = {
formSubmitionResult:null
}


This is a jQuery Mobile question, but it also relates to pure jQuery.

How can I post form data without page transition to the page set into form action attribute. I am building phonegap application and I don't want to directly access server side page.

I have tried few examples but each time form forwards me to the destination php file.

解决方案

Intro

This example was created using jQuery Mobile 1.2. If you want to see recent example then take a look at this article or this more complex one. You will find 2 working examples explained in great details. If you have more questions ask them in the article comments section.

Form submitting is a constant jQuery Mobile problem.

There are few ways this can be achieved. I will list few of them.

Example 1 :

This is the best possible solution in case you are using phonegap application and you don't want to directly access a server side php. This is an correct solution if you want to create an phonegap iOS app.

index.html

<!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/index.js"></script>
</head>
<body>
    <div data-role="page" id="login" data-theme="b">
        <div data-role="header" data-theme="a">
            <h3>Login Page</h3>
        </div>

        <div data-role="content">
            <form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
                <fieldset>
                    <div data-role="fieldcontain">
                        <label for="username">Enter your username:</label>
                        <input type="text" value="" name="username" id="username"/>
                    </div>                                  
                    <div data-role="fieldcontain">                                      
                        <label for="password">Enter your password:</label>
                        <input type="password" value="" name="password" id="password"/> 
                    </div>
                    <input type="button" data-theme="b" name="submit" id="submit" value="Submit">
                </fieldset>
            </form>                              
        </div>

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

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

        <div data-role="content">

        </div>

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

check.php :

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

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

    // Lets say everything is in order
    echo "Username = ";
?>

index.js :

$(document).on('pagebeforeshow', '#login', function(){  
        $(document).on('click', '#submit', function() { // catch the form's submit event
        if($('#username').val().length > 0 && $('#password').val().length > 0){
            // Send data to server through ajax call
            // action is functionality we want to call and outputJSON is our data
                $.ajax({url: 'check.php',
                    data: {action : 'login', formData : $('#check-user').serialize()}, // Convert a form to a JSON string representation
                        type: 'post',                   
                    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) {
                            resultObject.formSubmitionResult = result;
                                        $.mobile.changePage("#second");
                    },
                    error: function (request,error) {
                        // This callback function will trigger on unsuccessful action                
                        alert('Network error has occurred please try again!');
                    }
                });                   
        } else {
            alert('Please fill all nececery fields');
        }           
            return false; // cancel original event to prevent form submitting
        });    
});

$(document).on('pagebeforeshow', '#second', function(){     
    $('#second [data-role="content"]').append('This is a result of form submition: ' + resultObject.formSubmitionResult);  
});

var resultObject = {
    formSubmitionResult : null  
}

这篇关于jQuery Mobile:如何正确地提交表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆