geri ajax çağrısından json veri almak

1 Cevap php

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 my website Because it diddn't work, I created a minimized portion off the code to check if it had something to do with the json method.

I only tested if I could get a sessionname back after the phpscript was proccessed What I get back is "undefined" instead of "johndoe".

I have no idea what could be the problem. Obviously, the script has worked fine for others, if you see the comments on the creators page.

bu benim testingcode olduğunu

<?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
//the php script

if ($_GET['action'] == "startjson") { startjsonSession(); } 



function startjsonSession() {
    $items = '';


    /*if (!empty($_SESSION['openChatBoxes'])) {
    	foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
    		$items .= chatBoxSession($chatbox);
    	}
    }


    if ($items != '') {
    	$items = substr($items, 0, -1);
    }*/

header('Content-type: application/json');
?>
{
    	"username": "<?php echo $_SESSION['username'];?>",
    	"items": [
    		<?php echo $items;?>
        ]
}

<?php


    exit(0);
}

?>

teşekkürler, Richard

1 Cevap

Richard, PHP json_encode() fonksiyonuna içine bakmak gerekir. Hızla JSON için dizi dönüştürmek ve büyük miktarda veri ile JSON sözdizimi küçük nüansları ile uğraşmak zorunda tutmak.


Güncelleme: Modifiye Kodu

<?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"
    		)
    	));
    }
?>