PHP从PostgreSQL取state_name,Angular填充下拉框显示undefined问题
问题分析与解决方案
核心问题:浏览器请求getstate_shikhartest2.php时,服务器未解析PHP代码,直接返回了文件源码,导致Angular拿到的不是预期的JSON数据,下拉框因此显示undefined。终端能正常运行PHP是因为直接调用了PHP解析器,但浏览器访问时走Web服务流程,若服务未配置PHP解析就会返回源码。
解决步骤
1. 使用Web服务器托管文件
不能通过file://协议直接打开本地HTML文件,必须将所有文件放在Web服务器(如XAMPP、WAMP、Nginx、Apache)的根目录下,通过http://localhost/开头的地址访问。
2. 验证PHP文件是否正确返回JSON
在浏览器地址栏直接访问http://localhost/getstate_shikhartest2.php,正常情况下应看到类似以下的JSON结果:
[{"state_name":"北京"},{"state_name":"上海"},...]
如果仍显示PHP源码,说明Web服务器未启用PHP解析模块,需检查配置:
- Apache:确保
httpd.conf中已加载php_module,且添加了.php文件的处理规则:AddType application/x-httpd-php .php - XAMPP/WAMP:确保服务器已启动,且PHP服务处于运行状态。
3. 前端代码微调(可选)
当前前端逻辑正确,可添加数据校验避免非JSON数据导致的错误:
<!DOCTYPE html> <html lang="en" ng-app="MyApp"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Dropdown List</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script> </head> <body ng-controller="MyController"> <h1>Dynamic Dropdown List</h1> <hr /> <div> States: <select ng-model="selectedState" name="states" ng-options="state.state_name for state in states"> <option value="">--Select State--</option> </select> </div> <script> var app = angular.module("MyApp", []); app.controller('MyController', ['$scope', '$http', function ($scope, $http) { $http.get('getstate_shikhartest2.php').then(function (response) { if (Array.isArray(response.data)) { $scope.states = response.data; } else { console.error('Invalid data format:', response.data); $scope.states = []; } console.log('Retrieved data:', $scope.states); }, function (error) { console.error('Error fetching data:', error); $scope.states = []; }); }]); </script> </body> </html>
4. PHP代码确认(当前代码无问题)
你的PHP代码逻辑正确,服务器解析后会返回标准JSON:
<?php error_reporting(E_ALL); ini_set('display_errors', '1'); $host = "localhost"; $username = "postgres"; $password = "sanskriti"; $database = "sanskriti"; // Connect to the database $conn = pg_connect("host=$host dbname=$database user=$username password=$password"); // Check connection if (!$conn) { die("Connection failed: " . pg_last_error()); } // Set the character set to UTF-8 pg_set_client_encoding($conn, "UTF8"); $output = []; $result = pg_query($conn, "SELECT state_name FROM public.mstate2"); if (!$result) { $error = ['error' => 'Query execution failed']; header('Content-Type: application/json; charset=utf-8'); echo json_encode($error, JSON_UNESCAPED_UNICODE); exit; } while ($row = pg_fetch_assoc($result)) { $output[] = $row; } // Close the connection pg_close($conn); // Set content type and echo JSON with UTF-8 encoding header('Content-Type: application/json; charset=utf-8'); echo json_encode($output, JSON_UNESCAPED_UNICODE); ?>
验证流程
- 启动Web服务器,将HTML和PHP文件放入服务器根目录;
- 访问
http://localhost/shikhar.test.html; - 打开浏览器控制台,查看
Retrieved data日志,确认是否为正确的数组数据; - 下拉框应正常显示所有州名。
内容的提问来源于stack exchange,提问作者SHIKHAR SURYAVANSHI
相关产品推荐
相关产品推荐

