json_encode() 不返回任何内容
我有一个 PHP 脚本,它使用 json_encode() 方法解析数组,但返回空白
PHP 代码如下
$companies = $db->getCustomerNames();
print_r($companies)
if (!empty($companies)){
$jsonstring = json_encode($companies);
echo $jsonstring ;
}
else{
echo 'false';
}
- $companies 已填充,我可以将其打印出来,但
我也有一个如下所示的 javascript
jQuery.ajax({
type: "GET",
url: "http://localhost/myscript.php"
success: function(msg) {
companies = jQuery.parseJSON(msg);
//DO OTHER STUFF WITH companies
}
});
- PHP 脚本连接到DB 并回显 JSON 编码数组
- Javascript 使用 AJAX 获取数组,这样我就可以使用它的内容
- 当我点击 http://localhost/myscript.php 我得到一个空白页面
- 在我的本地服务器上运行良好
- 该页面托管在雅虎上(不确定是否有什么区别)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果数组像您在问题文本中提到的那样显示,则说明有问题。该页面应该显示类似的内容,
您也可以发布相关的 PHP 代码吗?
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
Could you post the relevant PHP code as well please?
尝试使用 function_exist 因为在某些服务器上 json* 函数可能被禁用或 php 配置为不使用它
Try to use function_exist because on some servers json* functions could be disabled or php is configured to not use it
首先执行
print_r($companies)
然后执行echo $jsonstring;
删除 print_r 行,因为响应当然不会是有效的 JSON 字符串。还要尝试在执行 echo 之前添加
header("Content-Type: text/plain");
,并确保将该字符串放在任何输出之前。First you do
print_r($companies)
then you doecho $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.你的js是正确的,正如JohnP所说,当你点击 http://localhost/myscript.php 你应该得到数组显示为 [“IBM”、“EDS”、“MICROSOFT”]。检查您是否有类似以下代码:
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: