簡體   English   中英

無法使用jQuery mobile和php發布表單並接收相關數據

[英]Can't post a form and receive relative data with jQuery mobile and php

我想使用AJAX發布登錄表單,然后使用PHP頁面驗證憑據,創建會話,然后重定向到保護頁面。 我有4個文件,index.php(包含登錄表單),index.js(包含用於發布的javascript代碼),check.php(檢查憑據並創建會話的頁面),home.php(受保護的頁面)。

的index.php

<!DOCTYPE html>
<html>
<head>
<title>cieimpel</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.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script> 
<script src="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>
</body>
</html>

index.js

$(document).on('pageinit', '#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 the ajax call
        // action is functionality we want to call and outputJSON is our data
        $.ajax({
            url: 'check.php',
            data: {
                formData: $('#check-user').serialize()
            },
            type: 'POST',
            async: 'true',
            dataType: 'json',
            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.status) {
                    if (result.login) {
                        $.mobile.changePage("home.php");
                    } else {
                        alert("wrong credentials " + result.username);
                    }
                } else {
                    alert("errore");
                }
            },
            error: function (request, error) {
                // This callback function will trigger on unsuccessful action                
                alert("An error occurred: " + status + "nError: " + error);
            }
        });
    } else {
        alert('Please fill all necessary fields');
    }
    return false; // cancel original event to prevent form submitting
});
});

check.php

<?php
// Prevent caching.
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 1996 00:00:00 GMT');

// The JSON standard MIME header.
header('Content-type: application/json');

// Decode JSON object into readable PHP object
$formData = json_decode($_POST['formData']); 

// Get username
$username = $formData->{'username'}; 
// Get password
$password = md5($formData->{'password'});  


if ($username == "pippoooo"){
    $output = array('status' => true, 'login' => true);
    echo json_encode($output);
    setcookie('LOGIN', $username, time()+72000);
}else{
    $output = array('status' => true, 'login' => false, 'username' => $username);
    echo json_encode($output);
}
?>

home.php

<?php
if(!isset($_COOKIE['LOGIN'])){
    header("Location: index.php");
}
?>


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
home.php
</body>
</html>

現在,如果我在check.php中寫一條類似於$ username =“ pippoooo”的行,那么一切進展順利,所以我懷疑formData為空。 誰知道錯誤在哪里?

編輯:好的,我可以確定問題出在:

$formData = json_decode($_POST['formData']); 

我使用chrome開發人員的工具控制了請求,並且發送的formData是正確的。 問題在於在check.php頁面中接收已發布的數據,該數據為null。

要求 回應

$ _POST中的JQuery Mobile POST數據為空

這個問題有解決我的問題的方法。 我只是脫下

contentType: 'json',

來自AJAX請求和標頭

// The JSON standard MIME header.
header('Content-type: application/json');

從check.php頁面。 這樣,將填充$ _POST數組。

我還對index.js中的ajax請求以及check.php中的表單字段值的收集做了一些小的更改。 工作代碼:

的index.html

<!DOCTYPE html>
<html>
<head>
<title>cieimpel</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.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="index.js"></script>    
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.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>
</body>
</html>

index.js

$(document).on('pageinit', '#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 the ajax call
            // action is functionality we want to call and outputJSON is our data

            console.log($('#check-user').serialize());
            $.ajax({
                url: 'check.php',
                data: $('#check-user').serialize(),
                type: 'POST',
                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) {
                    console.log(result);
                },
                error: function (request, error) {
                    // This callback function will trigger on unsuccessful action                
                    alert("An error occurred: " + status + "nError: " + error);
                }
            });
        } else {
            alert('Please fill all necessary fields');
        }
        event.preventDefault(); // cancel original event to prevent form submitting
    });
});

check.php

<?php
// Prevent caching.
header('Cache-Control: no-cache, must-revalidate');

// Get username
$username = $_POST['username'];
// Get password
$password = md5($_POST['password']); 

if ($username == "pippoooo"){
    // Lets say everything is in order
    $output = array('status' => true, 'login' => true);
    echo json_encode($output);
    setcookie('LOGIN', $username, time()+72000);
}else{
    // Lets say everything is in order
    $output = array('status' => true, 'login' => false, 'username' => $username);
    echo json_encode($output);
}
?>

感謝DraganGaić的協助和原始代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM