php - 为什么这个简单的 JSON 编码不起作用?

标签 php jquery json

我有一个生成 JSON 对象的 PHP 页面。 我有一个使用 jquery 库的页面,我想从中访问该对象。 但这不起作用。我看到消息“inside_nk”而不是“inside_ok”。为什么? 我已尝试尽可能简化我的代码。

prueba.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/prueba.js"></script>
</head>
<body>
</body>
</html>

普鲁巴PHP

<?php
header('Content-type: application/json; charset=utf-8');

class c1 {
    var $i = 0;
    var $e = 1;
    function c1() {}
}

$inst_c1 = new c1();

echo json_encode($inst_c1);
?>

prueba.js

$(document).ready(function() {
alert('begin');
$.ajax({
    url: 'http://[myserver]/prueba.php',
    dataType: 'json',
    data: '',
    success: function (data) { alert('inside_ok'); },
    error: function (data) { alert('inside_nk'); },
});
alert('end');
});

注意: 我尝试使用 "url: 'http://[myserver]/prueba.php?callback=?',"

 "dataType: 'jsonp'". 
 http://[myserver]/prueba.php

有效。我用 Firebug 检查过。

最佳答案

如果您要使用 json_encode 我认为最好在 array() 而不是对象上使用它:

$out = array("i" => 0, "e" => 1);
echo json_encode($out);

关于php - 为什么这个简单的 JSON 编码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7437541/

相关文章:

javascript - 为什么我在所有 HTML 内容下方都有一大片空白区域?

javascript - jQuery点击事件自定义属性未定义

c# - 创建嵌套的子 JSON

java - 使用 Jackson 转换为 JSON 时处理空 XML 节点

php - 如何从 Yii 网页和 Python 执行 MonkeyRunner

javascript - 如何将具有相同类名的多个id值作为数组发送到ajax到codeigniter中的数据库?

php - (double) $user_input 和 bind_param ('d' , $user_input 之间的安全差异

php mysql 没有以正确的方式更新行

javascript - 如何读取从 ajax 返回的数据数组以获取 google 图表?

JavaScript 选择类似数组的对象?