ゴール:
json_encode
プライベートプロパティを持つPHPオブジェクト- jQueryを使用して低レベルAJAXを介してエンコードされたオブジェクトをデータ文字列として送信します
json_decode
リクエストの送信先となるAJAXURLの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)に送信されている引数$json_strとエラーコードを示しています。