sending JSON as AJAX reponse. json_encode just not working?
Ive done some work before with encoding arrays into json objects and sending them, however this I just cannot get json-encode to work...
My script for sending out for the ajax response is as follows...
function loadCalls(sid)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
innerText = xmlhttp.responseText;
aCall = document.createElement('div');
aCall.innerHTML = innerText;
document.getElementById("calls").appendChild(aCall);
}
}
xmlhttp.open("POST","loadCalls.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=<? echo $fname; ?>&lname=<? echo $lname; ?>&email=<? echo $email; ?>&sid=" + sid);
}
And my php form code is as follows... What it simply does is build an array try to encode it to JSON, and then send it back to my loadCalls function above.
//Lets grab the uber long variable...
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$sid = $_POST['sid'];
//Array for all the tokens to go into...
$ourCalls = array();
//Our counter
$i = 0;
//Build the query
$querytokens = "SELECT * FROM lime_tokens_".$sid." WHERE firstname='".$fname."' AND lastname ='".$lname."'";
//execute query
$resulttokens = mysql_query($querytokens) or die ("Error in query: $querytokens. ".mysql_error());
// see what rows were returned
while($rowtokens = mysql_fetch_row($resulttokens)) {
$ourCalls[$i] = $rowtokens[5];
$i++;
}
echo json_encode($ourCalls);
// free result set memory
mysql_free_result($resulttokens);
// close connection
mysql_close($开发者_如何学Cconnection);
If i just echo our the print_r $ourCalls, i get that text displayed, and my line of thought is that even if i left the code in part one the way i wanted, it would still show on my screen as the string. But i get nothing.
Please help :)
EDIT
The output of the print_r is :
Array ( [0] => b8r5x6w53d6cahw [1] => p5ugbeg68b4qixy ) 1
Array ( [0] => 4c85zznh955gjsc [1] => 2atggeb2hyg9mbj ) 1
Array ( [0] => z4kihguxfu2npx9 ) 1
What does the 1 at the end mean?
EDIT - dropped the echo, 1's are now gone.
Make sure you are using php 5.2+, as json_encode() does not exist in previous versions
I cannot see your delimiters ? , and ; and {} ?
精彩评论