2016-10-17 3 views
0

내 AngularJS HTTP 서비스가 항상 상태 -1의 오류를 반환하는지 궁금합니다.AngularJS의 HTTP 서비스는 항상 오류를 반환합니다.

PHP 코드가 있으며 localhost/ajax.php로 실행하십시오. 이 파일은 데이터베이스에서 데이터를 검색 할 수 있습니다. 그래서 PHP는 잘 작동합니다. 검색된 데이터는 다음과 같습니다 :

[{"id":"1","Name":"Mark","Gender":"Male","City":"London"}, 
{"id":"2","Name":"John","Gender":"Male","City":"Chenni"}, 
{"id":"3","Name":"Hint","Gender":"Male","City":"Singapore"},  
{"id":"4","Name":"Sara","Gender":"Female","City":"Sydney"}, 
{"id":"5","Name":"Tom","Gender":"Male","City":"New York"}, 
{"id":"6","Name":"Pam","Gender":"Male","City":"Los Angeles"}, 
{"id":"7","Name":"Catherine","Gender":"Female","City":"Chicago"}, 
{"id":"8","Name":"Mary","Gender":"Femal","City":"Houston"}, 
{"id":"9","Name":"Mike","Gender":"Male","City":"Phoenix"}, 
{"id":"10","Name":"Rosie","Gender":"Female","City":"Manchestor"}, 
{"id":"11","Name":"Lim","Gender":"Male","City":"Singapore"}, 
{"id":"12","Name":"Tony","Gender":"Male","City":"Hong Kong"}, 
{"id":"13","Name":"Royce","Gender":"Male","City":"London"}, 
{"id":"14","Name":"Hitler","Gender":"Male","City":"Germany"}, 
{"id":"15","Name":"Tommy","Gender":"Male","City":"New Jersy"}] 

이 PHP 파일은 내 AngularJS HTTP 서비스에서 호출되었지만 해당 호출은 항상 상태 -1의 오류를 반환합니다.

나는 모든 자료를 보았지만 아무런 단서도 없었다. 내 데이터베이스는 Sql을 사용하여 localhost에 설치됩니다.

내 검색어가 오류 일 수 있습니다. 나는 그것들이 에러 상태 -1로 http 서비스를 반환한다고 생각한다.

Ajax.php

<?php 
    require 'connect.php'; 

    $connect = connect(); 

    // Get the data 
    $students = array(); 
    $sql = "SELECT id, Name, Gender, City FROM tblStudents"; 

    if($result = mysqli_query($connect,$sql)) 
    { 

     $count = mysqli_num_rows($result); 
     $cr = 0; 
     while($row = mysqli_fetch_assoc($result)) 
     { 
      $students[$cr]['id'] = $row['id']; 
      $students[$cr]['Name'] = $row['Name']; 
      $students[$cr]['Gender'] = $row['Gender']; 
      $students[$cr]['City'] = $row['City'];   
      $cr++;   
     } 
    } 

    $json = json_encode($students); 
    echo $json; 
    exit; 

?> 

connect.php

<?php 
    // db credentials 
    define('DB_HOST', 'localhost'); 
    define('DB_USER','root'); 
    define('DB_PASS','nyan'); 
    define('DB_NAME','Students'); 

    // Connect with the database. 
    function connect() 
    { 
     $connect = mysqli_connect(DB_HOST ,DB_USER ,DB_PASS ,DB_NAME); 

     if (mysqli_connect_errno($connect)) 
     { 
     die("Failed to connect:" . mysqli_connect_error()); 
     } 

     mysqli_set_charset($connect, "utf8"); 


     return $connect; 
    } 


?> 

Script.js

var app = angular.module("Demo", ["ngRoute"]) 
       .config(function($routeProvider){ 
       $routeProvider 
       .when("/home", { 
        templateUrl:"Templates/home.html", 
        controller:"homeController" 
       }) 
       .when("/courses", { 
        templateUrl:"Templates/courses.html", 
        controller:"coursesController" 
       }) 
       .when("/students", { 
        templateUrl:"Templates/students.html", 
        controller:"studentsController" 
       }) 
      })    
      .controller("homeController", function($scope){ 
       $scope.message = "Home Page"; 
      }) 
      .controller("coursesController", function($scope){ 
       $scope.courses = ["C#", "VB.NET", "SQL Server", "ASP.NET"]; 
      }) 
      .controller("studentsController", function ($scope, $http) { 
       $scope.students; 
       $http({      
        method: 'GET', 
        url: 'api/ajax.php' 
       }).then(function (response) { 
        $scope.students = response.data; 
       }, function (response) { 
        console.log(response.data,response.status); 
       });     
      }); 

index.html을

다음과 같이 있습니다

내 코드입니다

<!DOCTYPE html> 
<!-- 
To change this license header, choose License Headers in Project Properties. 
To change this template file, choose Tools | Templates 
and open the template in the editor. 
--> 
<html ng-app="Demo"> 
    <head> 
     <title>TODO supply a title</title> 
     <meta charset="UTF-8"> 
     <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
     <script src="Scripts/angular.min.js" type="text/javascript"></script> 
     <script src="Scripts/angular-route.min.js" type="text/javascript"></script> 
     <script src="Scripts/Script.js" type="text/javascript"></script> 
     <link href="Styles.css" rel="stylesheet" type="text/css"/>   
    </head> 
    <body >   
     <table style="font-family: Arial"> 
      <tr> 
       <td colspan="2" class="header"> 
        <h1> 
         WebSite Header 
        </h1> 
       </td> 
      </tr> 
      <tr ng-controller="studentsController"> 
       <td class="leftMenu"> 
        <a href="#/home">Home</a> 
        <a href="#/courses">Courses</a> 
        <a href="#/students">Students</a> 
       </td> 
       <td class="mainContent"> 
        <ng-view></ng-view>      
       </td> 
      </tr> 
      <tr> 
       <td colspan="2" class="footer"> 
        <b>Website Footer</b> 
       </td> 
      </tr> 
     </table> 
    </body> 
</html> 
+1

header ('Content-Type : application/json');을 추가하십시오. json 결과를 Ajax.php에 에코하기 전에 – 11mb

+0

@ 11MB 무엇을합니까? 나는 어떤 차이도 보이지 않는다. – batuman

+0

json 형식으로 결과를 기대하는 각도를 알려줍니다. (http://stackoverflow.com/questions/4064444/returning-json-from-a-php-script) "내 쿼리는 HTTP 서비스가 오류와 함께 반환되는 오류 소스 일 수 있습니다." ? ajax.php에서 데이터베이스를 쿼리하지 않고 json 문자열을 echo 할 때 Ajax 호출이 작동합니까? – 11mb

답변

0

마지막으로, 정말로 마침내 만들 수있었습니다. 다음 코드는 프로세스가 작동하도록합니다.

index.php를

<!DOCTYPE html> 
<!-- 
To change this license header, choose License Headers in Project Properties. 
To change this template file, choose Tools | Templates 
and open the template in the editor. 
--> 
<html> 
    <head> 
     <meta charset="UTF-8"> 
     <title></title>  
     <script src="Scripts/angular.min.js" type="text/javascript"></script> 
     <script src="Scripts/angular-route.js" type="text/javascript"></script>   
     <script src="Scripts/Script.js" type="text/javascript"></script> 
     <link href="Styles.css" rel="stylesheet" type="text/css"/> 
    </head> 
    <body ng-app="Demo"> 
     <table style="font-family: Arial"> 
      <tr> 
       <td colspan="2" class="header"> 
        <h1> 
         WebSite Header 
        </h1> 
       </td> 
      </tr> 
      <tr> 
       <td class="leftMenu"> 
        <a href="#/home">Home</a> 
        <a href="#/courses">Courses</a> 
        <a href="#/students">Students</a> 
       </td> 
       <td class="mainContent"> 
        <ng-view></ng-view>      
       </td> 
      </tr> 
      <tr> 
       <td colspan="2" class="footer"> 
        <b>Website Footer</b> 
       </td> 
      </tr> 
     </table> 
    </body> 
</html> 

database.php

<?php 

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
    class Database{ 

     // specify your own database credentials 
     private $host = "localhost"; 
     private $db_name = "Students"; 
     private $username = "root"; 
     private $password = "nyan"; 
     public $conn; 

     // get the database connection 
     public function getConnection(){ $this->conn = null; 

      try{ 
       $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password); 
      }catch(PDOException $exception){ 
       echo "Connection error: " . $exception->getMessage(); 
      } 

      return $this->conn; 
     } 
    } 
?> 

Students.php

<?php 

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
    class Students{ 
     // database connection and table name 
     private $conn; 
     private $table_name = "tblStudents"; 

     // object properties 
     public $id; 
     public $name; 
     public $gender; 
     public $city; 

     // constructor with $db as database connection 
     public function __construct($db){ 
      $this->conn = $db; 
     } 
     // read products 
     public function readAll(){ 

      // select all query 
      $query = "SELECT 
         id, name, gender, city 
        FROM 
         " . $this->table_name . " 
        ORDER BY 
         id"; 

      // prepare query statement 
      $stmt = $this->conn->prepare($query); 

      // execute query 
      $stmt->execute(); 

      return $stmt; 
     } 
    } 

?> 

ReadStudents.PHP

<?php 

    // include database and object files 
    include_once 'database.php'; 
    include_once 'Students.php'; 

    // instantiate database and product object 
    $database = new Database(); 
    $db = $database->getConnection(); 

    // initialize object 
    $students = new Students($db); 

    // query products 
    $stmt = $students->readAll(); 
    $num = $stmt->rowCount(); 

    $data=""; 

    // check if more than 0 record found 
    if($num>0){ 

     $x=1; 

     // retrieve our table contents 
     // fetch() is faster than fetchAll() 
     // http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop 
     while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ 
      // extract row 
      // this will make $row['name'] to 
      // just $name only 
      extract($row); 

      $data .= '{'; 
       $data .= '"id":"' . $id . '",'; 
       $data .= '"name":"' . $name . '",'; 
       $data .= '"gender":"' . $gender . '",'; 
       $data .= '"city":"' . $city . '"'; 
      $data .= '}'; 

      $data .= $x<$num ? ',' : ''; $x++; } 
    } 

    // json format output 
    echo '{"records":[' . $data . ']}'; 

?> 

Script.js

var app = angular.module("Demo", ["ngRoute"]) 
       .config(function($routeProvider){ 
       $routeProvider 
       .when("/home", { 
        templateUrl:"Templates/home.html", 
        controller:"homeController" 
       }) 
       .when("/courses", { 
        templateUrl:"Templates/courses.html", 
        controller:"coursesController" 
       }) 
       .when("/students", { 
        templateUrl:"Templates/students.html", 
        controller:"studentsController" 
       }) 
      }) 

      .controller("homeController", function($scope){ 
       $scope.message = "Home Page"; 
      }) 
      .controller("coursesController", function($scope){ 
       $scope.courses = ["C#", "VB.NET", "SQL Server", "ASP.NET"]; 
      }) 
      .controller("studentsController", function ($scope, $http) { 
       $http.get("api/ReadStudents.php").success(function(response){ 
        $scope.students = response.records; 
       });     
      }); 

courses.html

<h1>Courses we offer</h1> 
<ul> 
    <li ng-repeat="course in courses">{{course}}</li> 

</ul> 

home.html을

<h1>{{message}}</h1> 
<div> 
    PRAGIM established in 2000 by 3 s/w engineers offers very cost effective training. 
</div> 
<ul> 
    <li>Training delivered by real time softwares experets</li> 
    <li>Realtime project discussion relating to the possible interview questions</li> 
    <li>Trainees can attend training and use lab untill you get a job</li> 
    <li>Resume preparation and mockup interviews</li> 
    <li>100% placement assistant</li> 
    <li>lab facility</li> 
</ul> 

students.html

<h1>List of students</h1> 
<ul > 
    <li ng-repeat="student in students">{{student.name}}</li>  
</ul> 
+0

우선 ... 나는 당신의 답이 당신의 문제에 대한 단서가 없다. 당신에게 엄청난 양의 코드를 보았다. 두 번째 : 질문의 코드가 답안 코드와 닮아 있지 않습니다. 귀하의 질문에 당신은 당신의 대답에 갑자기 PDO로 전환 한 mysqli를 사용합니다 (그런데 더 나은 선택)? .. 귀하의 질문에 당신의 대답이 어디에 속하는지 구체적으로 밝히고 귀하의 문제를 해결하는 데 도움이되었던 것을 분명히 이해하기 위해 게시물을 최소한으로 유지하십시오. – DTH

+0

데이터베이스 액세스를 위해 phps가 크게 변경되었습니다. 나머지 코드는 다소 비슷합니다. PDO와 mysqli가 더 나은 선택입니다. 하지만 mysqli를 사용하여 작동하게 만들 수는 없었다. – batuman

0

질문에 데이터베이스 쿼리로 인해 스크립트가 손상되었다고 진술합니다.

쿼리에 시간이 오래 걸리면 시간 초과가 발생할 수 있습니다. 응답 코드 -1은 대개 요청이 중단되었음을 의미합니다. 각도 js 문서 https://docs.angularjs.org/api/ng/service/ $ http에 따라 config.timeout을 사용합니다.

당신은 당신의 시간 제한을 높이기 위해 시도 할 수 있습니다 : .. 요청이 걸리는 시간을 확인하기 위해 ajax.php 테스트 5 초로 설정됩니다이 예에서

$http.get('ajax.php', {timeout: 5000, method: 'GET'}); 

합니다.

편집 :

올바른 URL을 사용하고 있는지 확인하십시오. 귀하의 질문에 당신은 당신의 아약스 전화를 테스트하기 위해 다른 URL을 사용합니다.

+0

그는 각도의 방법을 사용할 수도 있습니다. 응답은 서버에서 올 때까지 기다립니다. – Jigar7521

+0

고마워요. 작동하지 않습니다. 타임 아웃까지 확장해도 10000입니다. – batuman

+0

@batuman 아약스 호출의 URL을 변경했습니다. – 11mb

관련 문제