简体   繁体   中英

AngularJS, PHP MySQL implementation returns PHP code instead of query result

I'm able to read values from a database using PHP. And then I'm trying to execute this PHP through AngularJS controller.

view1.js

angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/view1', {
        templateUrl: 'view1/view1.html',
        controller: 'View1Ctrl'
    });
}])

.controller('View1Ctrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('view1/view1.php').then(successCallback, errorCallback);

    function successCallback(response) {
        $scope.songs = response.data;
    }

    function errorCallback(error) {
        alert(error);
    }
}]);

view1.php

<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "songs"; /* Database name */

$con = mysqli_connect($host, $user, $password, $dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$sel = mysqli_query($con, "select * from description");
$data = array();

while ($row = mysqli_fetch_array($sel)) {
    $data[] = array("artist" => $row['artist'], "key" => 
$row['song_key'], "beat" => $row['beat']);
}

echo json_encode($data);

view1.html

<div ng-app="myApp.view1" ng-controller="View1Ctrl">
    {{songs}}
</div>

This is the code I've done and this returns not the db data. It returns the exact same PHP code for {{songs}} .

This probably happens because you are requesting PHP server (port 80) from the default npm server (port 8000), try changing get() request parameter to :

$http.get('http://localhost/view1/view1.php').then(successCallback, errorCallback);  

So it will not going through npm server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM