javascript 可通過 ajax 請求從 php 接收數(shù)組,步驟如下:創(chuàng)建 php 數(shù)組并轉(zhuǎn)換為 json 字符串。使用 ajax 請求發(fā)送 json 數(shù)據(jù)到 php 腳本。在 php 中處理請求并響應(yīng) json 數(shù)據(jù)。在 javascript 中接收響應(yīng)數(shù)據(jù)并解析為數(shù)組。
如何用 JavaScript 接收 PHP 數(shù)組
回答:
JavaScript 可以通過 AJAX 請求從 PHP 接收數(shù)組。
詳細(xì)步驟:
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
-
創(chuàng)建 PHP 數(shù)組:
$array = ['name' => 'John Doe', 'age' => 30];
關(guān)注:愛掏網(wǎng) -
將數(shù)組轉(zhuǎn)換為 JSON 字符串:
$json = json_encode($array);
關(guān)注:愛掏網(wǎng) -
使用 AJAX 請求發(fā)送 JSON 數(shù)據(jù):
const request = new XMLHttpRequest(); request.open('POST', 'php_script.php'); request.setRequestHeader('Content-Type', 'application/json'); request.send(json);
關(guān)注:愛掏網(wǎng) -
在 PHP 中處理請求并響應(yīng) JSON 數(shù)據(jù):
<?php header('Content-Type: application/json'); // 處理請求... $json = json_encode($data); // PHP 數(shù)組或其他數(shù)據(jù) echo $json; ?>
關(guān)注:愛掏網(wǎng) -
在 JavaScript 中接收響應(yīng)數(shù)據(jù)并將其解析為數(shù)組:
request.onload = function() { if (request.status === 200) { const data = JSON.parse(request.response); console.log(data); // 解析后的 PHP 數(shù)組 } };
關(guān)注:愛掏網(wǎng)
注意:
- 確保 PHP 和 JavaScript 代碼位于同一服務(wù)器上或具有 CORS 頭部。
- 數(shù)組鍵和值在 JSON 字符串中會(huì)自動(dòng)轉(zhuǎn)換成字符串。
以上就是js如何接收php數(shù)組的詳細(xì)內(nèi)容,更多請關(guān)注愛掏網(wǎng) - it200.com其它相關(guān)文章!
聲明:所有內(nèi)容來自互聯(lián)網(wǎng)搜索結(jié)果,不保證100%準(zhǔn)確性,僅供參考。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進(jìn)行處理。