dou426098 2011-04-21 05:05
浏览 27

使用jQuery的.get()来检索PHP数据

I'm using jQuery's .ajax() to post to a PHP file called process.php. Process.php has a lot of code in it, but for simplicity's sake, let's just say it contains <?php echo 'hello'; ?>.

Is this the proper jQuery to insert process.php's results into div.results? :

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

So far it doesn't seem to be working.

Here's the HTML/Javascript file

<!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>

Here's process.php (greatly simplified):

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

2条回答 默认 最新

  • doubo1871 2011-04-21 05:08
    关注

    If you simply want to place the resulting string back into an element, use load().

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

    However, looking at your code...

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

    ...shows you have misunderstood something. The correct anonymous function to assign to the success callback would be...

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

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等