$.ajax({
method: 'GET',
dataType: 'json',
success: function(data) {
for (i in data.messages) {
output(data.messages[i]);
}
}
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
PHP腳本可以輸出:
$messages = array(
array(
'id' => 1,
'message' => 'Awesome',
'sender' => array(
'id' => 1, 'name' => 'John',
),
),
);
echo json_encode(array('messages' => $messages));
通過AJAX發送使用JSON信息:使用
// Example data object, you can have this infinitely nested
var data = [
{id: 1, "message": "test" }
];
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
PHP腳本就可以這樣說的:
$data = json_decode(file_get_contents('php://input'), true);
// This becomes a simple 2D PHP array which is an exact representation as your JS object. The above example data can be output as:
foreach ($data as $message) {
echo $message['id'] . ' - ' .$message['message'];
}
嗯,貌似將它發送到網頁工作。現在,我將如何獲取每個元素? –
你是什麼意思抓住每一個元素?如從頁面發送到PHP?在JavaScript中使用JSON對其進行編碼並將其發送給PHP。或者我誤解了你的問題? –
對不起,我的意思是在讀取json元素一旦發送到頁面。我從來沒有處理過json元素,所以我不知道它的結構,也不知道如何循環它(或者在Laravel中調用每個部分像$ message-> sender_id)。 –