开发者

json_encode() return nothing

开发者 https://www.devze.com 2023-03-03 21:39 出处:网络
I have a PHP script that parses an array using the json_encode() method but returns blank The PHP Code is as follows

I have a PHP script that parses an array using the json_encode() method but returns blank

The PHP Code is as follows

$companies = $db->getCustomerNames();
print_r($companies)
if (!empty($companies)){
$jsonstring = json_encode($companies);
echo $jsonstring ; 
}
else{
    echo 'false';
}
  • $companies is populated and i can print it out yet

I also have a javascript that looks like this

jQuery.ajax({

    type: "GET",
    url: "http://localhost/myscript.php"
    success: function(msg) {
        companies = jQuery.parseJSON(msg);
        //DO OTHER STUFF WITH companies 
    }
});
  • The PHP script 开发者_运维百科connects to a DB and echo the JSON encoded array
  • The Javascript gets the array using AJAX so i can use it's content
  • When I hit http://localhost/myscript.php i get a blank page
  • Works fine on my local server
  • The page is hosted on Yahoo (not sure if it makes a difference)


If the array is displaying like you mention in the text of your question then something is wrong. That page should be displaying something like

["IBM","EDS","MICROSOFT"]

Could you post the relevant PHP code as well please?


Try to use function_exist because on some servers json* functions could be disabled or php is configured to not use it


First you do print_r($companies) then you do echo $jsonstring; Remove the print_r line, because ofcourse the response won't be a valid JSON string.

Also try to add header("Content-Type: text/plain"); before you do echo and be sure to put that string before ANY output.


Your js is right and as JohnP said when you hit http://localhost/myscript.php you should get the array displayed as ["IBM","EDS","MICROSOFT"]. Check if you have code similar to the below:

<?php
$a = array (0 =>'IBM' ,1=>'EDS' ,2=>'SUN' ,3=>'GOOGLE' ,4 => 'ORACLE'); 
echo json_encode($a);
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消