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

ヘッダー( 'Content-Type:application/json')を追加しようとしました。 jsonの結果をAjax.phpにエコーする前に – 11mb

+0

@ 11mbどうしますか?違いは見られません。 – batuman

+0

json形式で結果を期待するためにangularを指示します。 (http://stackoverflow.com/questions/4064444/returning-json-from-a-php-script)「私のクエリは、HTTPサービスがエラーで復帰しているエラーソースになる可能性があります」とはどういう意味ですか? ? ajax.phpのデータベースを照会せずにjson文字列をエコーすると、あなたの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

まず第一に..私はあなたの答えがあなたの問題にどこにあるのか分かりません。大量のコードを見てください。 Second:あなたの質問からあなたのコードはあなたの答えのコードに似ていません。あなたの質問では、答えでmysqliを使用しています。あなたは突然PDOに切り替えました(これはより良い選択です)?あなたの質問にあなたの答えがどこにあるかを特定し、あなたの問題解決に役立つものを明確に理解するために投稿を最小限に抑えてください。 – DTH

+0

データベースアクセスのためにphpsに大きな変更を加えました。残りのコードは多かれ少なかれ類似しています。 PDOとmysqliは良い選択であり、あまり確かではありません。しかし、私はmysqliを使用して動作させることができませんでした。 – batuman

0

あなたの質問には、データベースクエリのためにスクリプトが壊れている可能性があります。

クエリに時間がかかると、タイムアウトが発生することがあります。レスポンスコード-1は通常、リクエストが中止されたことを意味します。角度jsのドキュメントhttps://docs.angularjs.org/api/ng/service/ $ httpに従ってconfig.timeoutを使用します。

あなたはタイムアウトを長くしようとすることができます:

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

この例では、...あなたの要求にかかる時間の長さを表示するためにあなたのajax.phpをテスト5秒に設定されます。

編集:

また、あなたは右のURLを使用してください。あなたの質問では、あなたのAjax呼び出しをテストするために別のURLを使用します。

+0

彼は、angleのメソッドを使用することもできます。これは、応答がサーバーから来るまで待機します。 – Jigar7521

+0

ありがとうございます、私はタイムアウト:10000にも拡張します。 – batuman

+0

@batuman ajax呼び出しのURLを変更しました。 – 11mb

関連する問題