问题
<?php
$query = mysql_query("Select id, name From table");
while($row = mysql_fetch_array($query)) {
echo $_GET["jsoncallback"] . '(<option value='.$row['id'].'>'.$row['name'].'</option>)';
}
?>
When I echo result, it is error, how to fix it?
回答1:
Since you didn't write exactly what you're trying to do, i'm guessing you're trying to return a list of HTML options that a JS callback function will place in your document.
try this:
<?php
$options = '';
$query = mysql_query("Select id, name From table");
while ($row = mysql_fetch_array($query)) {
$options .= '<option value="'.$row['id'].'">'.$row['name'].'</option>' . "\n";
}
echo $_GET["jsoncallback"] . "('" . $options . "');";
?>
This will first create all the options as a string, and only then build the callback.
回答2:
You don't say where the error is, but presumably it is in JS:
- Terminate your statements with a
;
- Generate valid JS. You can't just shove a bunch of HTML in a JS function call. You need some sort of JavaScript object. json_encode will generate an Object or an Array. Or you could construct a string but escaping characters with special meaning, replacing new lines, and quoting the value.
- Sanity check your
$_GET
data to make sure it conforms to the syntax of JS function names.
Oh, I see you have tagged this as JSON-P, in that case:
Construct a single object with all the data, convert it to JSON with encode_json
, then wrap the whole thing with the callback( and );. Don't call the callback multiple times in a while loop.
回答3:
Are you sure jsoncallback is set? Try with this:
<?php
$jsoncallback = isset($_GET["jsoncallback"])? $_GET["jsoncallback"] : "";
$query = mysql_query("Select id, name From table");
while($row = mysql_fetch_array($query)) {
echo $jsoncallback . '(<option value='.$row['id'].'>'.$row['name'].'</option>)';
}
?>
回答4:
Given that you have not provided what error you are getting. I will suggest try this:
<?php
if(isset($_GET['jsoncallback']))
{
$query = mysql_query("Select id, name From table");
while($row = mysql_fetch_array($query)) {
echo $_GET["jsoncallback"] . '(<option value='.$row['id'].'>'.$row['name'].'</option>)';
}
}
else
echo "Jsoncallback not set.";
?>
回答5:
$_GET
doesn't usually return errors.
The possible point of error is your query.
Insert
echo mysql_error();
before your while
loop;
来源:https://stackoverflow.com/questions/8134415/error-when-echo-getjsoncallback