繁体   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