目标:
json_encode
具有私有属性的 PHP 对象- 使用 jQuery通过低级 AJAX将编码对象作为数据字符串发送
json_decode
请求发送到的 AJAX URL 中的 PHP 对象- 赢
问题:
在第 3 步,json_last_error返回 3 ( JSON_ERROR_CTRL_CHAR Control character error, possibly incorrectly encoded
)
班上:
class Stream {
private $limit;
private $type;
private $sort;
private $offset=0;
private $userID;
private $catID;
private $content = array();
private $num_posts;
function __construct(){
$a = func_get_args();
$i = func_num_args();
if (method_exists($this,$f='__construct'.$i)) {
call_user_func_array(array($this,$f),$a);
}
}
function __construct5($limit, $type, $sort, $userID, $catID){
$this->limit = $limit;
$this->type = $type;
$this->sort = $sort;
$this->userID = $userID;
$this->catID = $catID;
//$this->num_posts = $this->retrieveTotal();
//$this->setContent();
}
function __get($name) {
if(isset($this->$name)){
return $this->$name;
}
}
public function encodeJSON(){
foreach ($this as $key => $value){
if($key != 'content'){
$json->$key = $value;
}
}
return json_encode($json);
}
public function decodeJSON($json_str){
$json = json_decode($json_str, true);
echo '<br>error: '.json_last_error();
foreach ($json as $key => $value){
$this->$key = $value;
}
}
}
//create the object to be encoded
$strm = new Stream(5, 'toc', ' ', 1, ' ');
/*this test works
$d=$strm->encodeJSON();
$st = new Stream();
$st->decodeJSON($d);
*/
AJAX 函数:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//load more posts
$("#active").live("click", function() {
var stream= '<?= $strm->encodeJSON();?>';
var dataString = 'stream='+stream;
var request = $.ajax({
type: "POST",
url: "ajax/loadmore.php",
data: dataString,
beforeSend:function(data){
$('.load-more').html('<img src="ajax/loader.gif" alt="Loading..." />');
},
success: function(html) {
$('#active').remove();
$('#stream').append(html);
}
});
//ajax error reporting
request.fail(function(jqXHR, textStatus) {
$('#active').html(textStatus);
});
});
</script>
<a class='load-more' id='active'>load more posts</a>
AJAX 请求(loadmore.php):
require_once'../../classes/stream.class.php';
$strm = new Stream();
$strm->decodeJSON($_POST['stream']);
我试过的:
这段代码
$d=$strm->encodeJSON();
$st = new Stream();
$st->decodeJSON($d);
工作正常。这会让我相信 AJAX 会干扰解码。
我也尝试过更改$json = json_decode($json_str, true);
,$json = json_decode(utf8_encode($json_str), true);
但没有任何变化。
注意:建议我公开类属性不是解决方案
编辑:当我回显字符串时,{
"limit": "5",
"type": "toc",
"sort": " ",
"offset": "0",
"userID": "3",
"catID": " ",
"num_posts": "2"
}
被发送到 decodeJSON 它测试为有效
此屏幕截图显示了发送到 decodeJSON($json_str) 的 arg $json_str 和错误代码。