簡體   English   中英

使用jQuery的.get()檢索PHP數據

[英]Using jQuery's .get() to retrieve PHP data

我正在使用jQuery的.ajax()發布到名為process.php的PHP文件。 Process.php中包含很多代碼,但是為了簡單起見,我們只說它包含<?php echo 'hello'; ?> <?php echo 'hello'; ?>

這是將process.php結果插入div.results的正確jQuery嗎?

$.get('process.php', function(data) {
    $('.results').html(data);
});

到目前為止,它似乎不起作用。

這是HTML / Javascript文件

<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="UTF-8" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("form#form").submit(function() {
                var username = $('#username').attr('value');
                $.ajax({
                    type: 'POST',
                    url: 'process.php',
                    data: 'username=' + username,
                    success: function() {
                        $('form#form').hide(function() {
                            $.get('process.php', function(data) {
                                $('.results').html(data);
                            });
                        });
                    }
                });
                return false;
            });
        });
    </script>

</head>

<body id="body">

<form id="form" method="post">
    <p>Your username: <input type="text" value="" name="username" id="username" /></p>
    <input type="submit" id="submit" value="Submit" />
</form>

<div class="results"></div>

</body>

</html>

這是process.php (經過簡化):

<?php
    /* get info from ajax post */
    $username = htmlspecialchars(trim($_POST['username']));
    echo $username;
?>

如果只想將結果字符串放回元素中,請使用load()

$('.results').load('process.php');

但是,查看您的代碼...

$.ajax({
    type: 'POST',
    url: 'process.php',
    data: 'username=' + username,
    success: function() {
        $('form#form').hide(function() {
            $.get('process.php', function(data) {
                $('.results').html(data);
            });
        });
    }
});

...表明您誤解了某些內容。 分配給success回調的正確匿名函數將是...

function(data) {
   $('form#form').hide()
   $('.results').html(data);
}

您可以嘗試這樣的事情。

function ajax_login() {
    if ($("#username").val()) {
    $.post("/process.php", { username : $("#username").val() }, function(data) {
    if (data.length) {
        $("#login_form").hide();
        $("#login_result").html(data);
        }
    })
    } else {
        $("#login_result").hide();
    }

然后在process.php中,如果發布成功,則回顯一些文本。

process.php =>

if (isset($_POST['username'])
{
    echo 'hello '.$_POST['username'];
}

暫無
暫無

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

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