dongnao9525 2012-05-11 23:12
浏览 49

无法将JSON字符串从PHP文件传输到Jquery中的getJSON方法

This is what I want, on a PHP page called input.php the user submits a username by a html form. This gets stored into the MYSQL database. There is a page called results.php which querys the MYSQL database for all usernames.

What I need to happen is that every 5 or so seconds some jquery code (maybe getJSON) will get a JSON string from results.php (the same page). This JSON string may be updated as a user may of added more usernames on the input.php page.

This is the input.php file

        <form name="input" action="<?php $_SERVER['PHP_SELF']?>" method="post">
        Usernames: <input type="text" name="usernames" />
         <input type="submit" value="Submit" name="submit" />
    </form>

    <?php

    if(isset($_POST['submit'])) {
        $link = mysql_connect('', '', '');
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }

        $db_selected = mysql_select_db('', $link);
        if (!$db_selected) {
            die ('Can\'t use  : ' . mysql_error());
        }

        $result = mysql_query("INSERT INTO users(user_name)             VALUES('".$_POST['usernames']."')");
        if (!$result) {
            die('Invalid query: ' . mysql_error());
        }


    }
    ?>

This is the results.php file

    <script
        type="text/javascript" src="jquery-1.7.1.min.js"></script>
    <?php

    $link = mysql_connect('localhost', 'root', '');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }

    $db_selected = mysql_select_db('test', $link);
    if (!$db_selected) {
        die ('Can\'t use test : ' . mysql_error());
    }

    $result = mysql_query("SELECT user_name FROM users");
    if (!$result) {
        die('Invalid query: ' . mysql_error());
    }


    $names = array();

    while ($row = mysql_fetch_assoc($result)) {

        foreach ($row as $key => $val) {

            $names[][$key] = $val;
        }
    }

    echo json_encode($names);


    ?>
    <script type="text/javascript"> 




        $.getJSON("http://localhost/test/results.php", function(json){
            alert("JSON Data: " + json);
        });

    </script>



    <div></div>

I am stuck on what jquery to put or even if i'm doing this properly. The end result is like Gmail where you receive email without a page refresh. But my system would retrieve usernames from the database every 5 seconds without a page refresh. I have read about getJSON method and I am totally out of my depth with it so I may need some very in depth explanation. If im going about this objective the wrong way please let me know and inform me of good practises in how to go about this.

I try this url in my browser with no result apart from the echoed JSON string from the php code.

this is my JSON string

[{"user_name":"matt"},{"user_name":"matt"},{"user_name":"peter"},{"user_name":"jim"},{"user_name":"sam"}]

  • 写回答

3条回答 默认 最新

  • dongye1942 2012-05-11 23:17
    关注

    If you want to use results.php to do both things (i.e. display the usernames as well as respond to the JSON query) then you will need to split the file into two branches. Use a _GET variable to specify which branch. So for example, you would run .getJSON on results.php?json=true instead of just results.php. Now inside results.php have an if branch that checks for the existence of this _GET variable, and if so, grab the data you need, echo it in a json-encoded string, and then exit(). Do all this before anything else in results.php, even before the <script> tag .

    Edited to provide code: (edited from OP's question)

    <?php
        $link = mysql_connect('localhost', 'root', '');
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }
    
        $db_selected = mysql_select_db('test', $link);
        if (!$db_selected) {
            die ('Can\'t use test : ' . mysql_error());
        }
    
        $result = mysql_query("SELECT user_name FROM users");
        if (!$result) {
            die('Invalid query: ' . mysql_error());
        }
    
        $names = array();
    
        while ($row = mysql_fetch_assoc($result)) {
    
            foreach ($row as $key => $val) {
    
                $names[][$key] = $val;
            }
        }
    
        if (isset($_GET['json'])) {
            echo json_encode($names);
            exit();
        }
    
        ?>
        <script type="text/javascript" src="jquery-1.7.1.min.js"></script>
        <script type="text/javascript"> 
            $.getJSON("http://localhost/test/results.php?json=true", function(json){
                alert("JSON Data: " + json);
            });
        </script>
    
    
    
        <div></div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作