get json data back from ajax call

后端 未结 1 693
迷失自我
迷失自我 2021-01-15 22:23

my question is: How can my php script send json type data and received back into the success or complete function?

I was trying to get this chatfunction to work on m

相关标签:
1条回答
  • 2021-01-15 22:45

    Richard, you should look into the json_encode() function in PHP. It will convert your array to JSON quickly, and keep you from having to deal with the smaller nuances of JSON syntax with large amounts of data.


    Update: Modified Code

    <?php
    
        session_start(); 
        $_SESSION['username'] = "johndoe" ;// Must be already set
    
    ?>
    
    <script type="text/javascript" src="includes/jquery.js"></script>
    <script language="JavaScript">
    $(document).ready(function(){
    
        $("#testjson").click(function(e){
            startJsonSession();
            return false;
        });
    
        function startJsonSession(){  
            $.ajax({
                url: "jsontest.php?action=startjson",
                cache: false,
                dataType: "json",
                complete: function(data) {
                    username = data.username;
                    alert(username);
                }
    
            });
        }
    
    }); 
    </script>
    
    <?php
    
        if ($_GET['action'] == "startjson") { 
            startjsonSession(); 
        } 
    
        function startjsonSession() {
            $items = '';
    
            print json_encode(array(
                "username" => "bob",
                "items" => array(
                    "item1" => "sandwich",
                    "item2" => "applejuice"
                )
            ));
        }
    ?>
    
    0 讨论(0)
提交回复
热议问题