1 回答

TA貢獻2080條經驗 獲得超4個贊
那里的噪音太多了,我無法輕松地看出問題所在。
我不會嘗試推理出來,而是向您展示一個解決方案,它接收數據就像您硬編碼它一樣,向whiteboardData數組添加一個新元素,然后再返回它。我希望使用 fetch 而不是舊的 XMLHttpRequest,但我有點生疏了。這對我來說更容易。
HTML
<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoaded, false);
var jsonObj =
[ /* list of room objects */
{ /* a room object */
name: 'example',
id: 'numbers',
whiteboardData: [
{ /* a shape object */
color: [100, 150, 100],
pointList: [
{ /* a vector object*/
x: 100,
y: 100,
}
/* heaps of other vector objects */
]
}
], /* end of whiteboardData */
chatMessages: [
{ /* a message object */
sender: 'username',
content: 'hi'
}
/* heaps of other message objects */
]
}
/* heaps of other room objects */
];
function ajaxPostFormData(url, formData, onSuccess, onError)
{
var ajax = new XMLHttpRequest();
ajax.onload = function(){onSuccess(this);}
ajax.onerror = function(){onError(this);}
ajax.open("POST",url,true);
ajax.send(formData);
}
function onLoaded(evt)
{
let fd = new FormData();
fd.append('whiteboardData', JSON.stringify(jsonObj) );
ajaxPostFormData('blahBlah.php', fd, function(ajax){console.log(ajax.responseText)}, function(){} );
}
</script>
</head>
<body>
</body>
</html>
PHP
<?php
// blahBlah.php
var_dump($_POST['whiteboardData']);
$jsonObj = json_decode( $_POST['whiteboardData'] );
$newObj = new wbData(200,300,200, [new vec2d(0,0), new vec2d(10,10), new vec2d(100,100)] );
// append the new stuff
$jsonObj[0]->whiteboardData[] = $newObj;
var_dump( json_encode($jsonObj) );
//-----------------------------------
class wbData
{
public function __construct ($r,$g,$b, $pts=[])
{
$this->color = [$r, $g, $b];
//$this->pointList = [];
$this->pointList = $pts;
}
};
class vec2d
{
public function __construct($x=0, $y=0)
{
$this->x = $x;
$this->y = $y;
}
}
?>
結果在控制臺
string(164) "[{"name":"example","id":"numbers","whiteboardData":[{"color":[100,150,100],"pointList":[{"x":100,"y":100}]}],"chatMessages":[{"sender":"username","content":"hi"}]}]"
string(250) "[{"name":"example","id":"numbers","whiteboardData":[{"color":[100,150,100],"pointList":[{"x":100,"y":100}]},{"color":[200,300,200],"pointList":[{"x":0,"y":0},{"x":10,"y":10},{"x":100,"y":100}]}],"chatMessages":[{"sender":"username","content":"hi"}]}]"
- 1 回答
- 0 關注
- 84 瀏覽
添加回答
舉報