Error when echo $_GET[“jsoncallback”]

ぃ、小莉子 提交于 2019-12-04 06:58:29

问题


<?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:

  1. Terminate your statements with a ;
  2. 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.
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!