我有一個 PHP 腳本,在其中我將查詢的內容寫入 Postgresql 資料庫:
<?php
require_once 'connection.php';
$query1 = pg_query("This_is_my_query");
$instruction = "[";
while ($row = pg_fetch_array($query1)) {
$row1= $row['row1'];
$row2= $row['row2'];
$instruction .= "{name : '". $row1. "', y : ". $row2. "},";
}
$instruction .= "]";
echo $instruction;
?>
該echo $instruction給:
[{name : 'Prestation', y : 1}]
然后我有一個 JS 檔案,我嘗試在其中顯示和使用$instruction變數。
我使用 Ajax,我的腳本是:
$.ajax({
url : 'Path_To_Php_File_Is_OK', // requesting a PHP script
dataType : 'json',
type: "GET",
async : false,
success : function (data) { // data contains the PHP script output
alert(data);
},
error: function(data) {
alert('error');
},
})
結果是沒有呼叫成功函式,我有alert('error'). 但是當我使用 dataType 'text' 而不是 'Json' 時,成功功能沒問題,我有alert(data).
如何解釋這種行為?我怎么能決議 PHP 變數$instruction?
任何幫助將不勝感激,謝謝!
uj5u.com熱心網友回復:
- 無需手動創建 json 字串。只需構建和陣列并將其編碼為json_encode()
- 您必須在回應標頭中設定 JSON 內容型別
- 結束
?>標簽是多余的,不推薦使用(見PSR-12)
所以最終你的代碼應該是這樣的
<?php
require_once 'connection.php';
$query1 = pg_query("This_is_my_query");
$instructions = [];
while ($row = pg_fetch_array($query1)) {
$row1 = $row['row1'];
$row2 = $row['row2'];
$instructions[] = ['name' => $row1, 'y' => $row2];
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($instructions);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/389412.html
標籤:javascript php 阿贾克斯
