使用jQuery's .get()检索PHP数据

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

本文关键字:检索 PHP 数据 get jQuery 使用      更新时间:2023-09-26

我使用jQuery的.ajax()发送到一个名为process.php的PHP文件。Process.php中有很多代码,但为了简单起见,我们就说它包含<?php echo 'hello'; ?>

这是适当的jQuery插入process.php的结果到div.results ?:

$.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中,如果post成功,则回显一些文本。

process.php =>

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