Javascript 将参数传递到角度

Javascript 将参数传递到角度,javascript,angularjs,Javascript,Angularjs,我将创建一个控制器,它将在数据库中的选定表中列出一个选定字段,并将其传递给我的API 目前,我正在使用一个脏方法,即创建几个控制器,其中包含字段名和表名 controller.js .controller('ListDistinctCustomerCtrl', function($scope, $http) { var xhr = $http({ method: 'post', url: 'http://localhost/api/list-distinct.php?tabl

我将创建一个控制器,它将在数据库中的选定表中列出一个选定字段,并将其传递给我的API

目前,我正在使用一个脏方法,即创建几个控制器,其中包含字段名和表名

controller.js

.controller('ListDistinctCustomerCtrl', function($scope, $http) {
  var xhr = $http({
    method: 'post',
    url: 'http://localhost/api/list-distinct.php?table=customer&field=cust_code'
  });
  xhr.success(function(data){
    $scope.data = data.data;
  });
})

.controller('ListDistinctSupplierCtrl', function($scope, $http) {
  var xhr = $http({
    method: 'post',
    url: 'http://localhost/api/list-distinct.php?table=supplier&field=supp_code'
  });
  xhr.success(function(data){
    $scope.data = data.data;
  });
})
这是API文件

列出distinct.php

<?php
require_once '/config/dbconfig.php';
$table = $_GET['table'];
$field = $_GET['field'];
GetData($table,$field);

function GetData($tablename,$fieldname) {
    $sql = "SELECT distinct $fieldname as expr1 FROM $tablename order by expr1 asc";
    try {
        $db = getdb();
        $stmt = $db->prepare($sql);
        $stmt->execute();
        $data = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode(array('data' => $data));
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}
?>


我相信有一种更干净更好的方法可以做到这一点。

首先,如果您想通过$http传递参数,有一种更干净的方法:

$http( 
    {
       url: 'your url',
       method: 'GET or POST',
       params: {
         // list of params
       }
    }
);
现在,它对于代码维护和使用的可读性非常重要。 您可以将Factory用作服务并创建API服务

例如:

angular.module( 'yourModule' ).factory( 'ServiceAPI', [ '$http', function ( $http ) {

var factory = {};

//PUBLIC METHODS
factory.method = method;

function method() {
  return $http( 
           {
               url: 'your url',
               method: 'GET or POST',
               params: {
                 // list of params
               }
           }
        );
}

return factory;
} ] );
现在,您可以在控制器上注入ServiceAPI,并使用承诺http的方法函数进行响应

angular.module( 'your module' ).controller( 'Ctrl', [ '$scope', 'ServiceAPI' ,
function ( $scope, ServiceAPI ) {

  ServiceAPI.method.then( function ( data) {
      $scope.data = data;
    }, function(){console.err('error');} );
}
] );
AngularJS侧,现在清晰易读

我希望能对你有所帮助。
享受

首先,如果您想通过$http传递参数,有一种更干净的方法:

$http( 
    {
       url: 'your url',
       method: 'GET or POST',
       params: {
         // list of params
       }
    }
);
现在,它对于代码维护和使用的可读性非常重要。 您可以将Factory用作服务并创建API服务

例如:

angular.module( 'yourModule' ).factory( 'ServiceAPI', [ '$http', function ( $http ) {

var factory = {};

//PUBLIC METHODS
factory.method = method;

function method() {
  return $http( 
           {
               url: 'your url',
               method: 'GET or POST',
               params: {
                 // list of params
               }
           }
        );
}

return factory;
} ] );
现在,您可以在控制器上注入ServiceAPI,并使用承诺http的方法函数进行响应

angular.module( 'your module' ).controller( 'Ctrl', [ '$scope', 'ServiceAPI' ,
function ( $scope, ServiceAPI ) {

  ServiceAPI.method.then( function ( data) {
      $scope.data = data;
    }, function(){console.err('error');} );
}
] );
AngularJS侧,现在清晰易读

我希望能对你有所帮助。 享受

是时候

这是您案例的一个示例:

angular.module('starter')
.factory('services', services);

function services($http) {
        var services = {
            customer: customer,
            supplier: supplier,
        };
        return services;

        //customer service
        function customer() {
            var req = {
                method: 'POST',
                url: 'http://localhost/api/list-distinct.php?table=customer&field=cust_code',
                headers: {
                    'Accept' : 'application/json',
                    'contentType': "application/json"
                }
            };
            return $http(req);
        },

       //supplier service
        function supplier() {
            var req = {
                method: 'POST,
                url: 'http://localhost/api/list-distinct.php?table=supplier&field=supp_code',
                headers: {
                    'Accept' : 'application/json',
                    'contentType': "application/json"
                }
            };
            return $http(req);
        };
 }
然后在控制器中这样调用它们:

services.customer().then(
      function(response) {
      //do whatever is needed with the response
        console.log(response);
      },

      function (error) {
        console.log(error); 
      }
   );




services.supplier().then(
          function(response) {
          //do whatever is needed with the response
            console.log(response);
          },

          function (error) {
            console.log(error); 
          }
        );
是时候休息了

这是您案例的一个示例:

angular.module('starter')
.factory('services', services);

function services($http) {
        var services = {
            customer: customer,
            supplier: supplier,
        };
        return services;

        //customer service
        function customer() {
            var req = {
                method: 'POST',
                url: 'http://localhost/api/list-distinct.php?table=customer&field=cust_code',
                headers: {
                    'Accept' : 'application/json',
                    'contentType': "application/json"
                }
            };
            return $http(req);
        },

       //supplier service
        function supplier() {
            var req = {
                method: 'POST,
                url: 'http://localhost/api/list-distinct.php?table=supplier&field=supp_code',
                headers: {
                    'Accept' : 'application/json',
                    'contentType': "application/json"
                }
            };
            return $http(req);
        };
 }
然后在控制器中这样调用它们:

services.customer().then(
      function(response) {
      //do whatever is needed with the response
        console.log(response);
      },

      function (error) {
        console.log(error); 
      }
   );




services.supplier().then(
          function(response) {
          //do whatever is needed with the response
            console.log(response);
          },

          function (error) {
            console.log(error); 
          }
        );

您可以创建一个包含访问API方法的服务。这将使您能够减少控制器中的代码重复,并允许更干净的代码

.service('APIService', function($http){
    var base = 'http://localhost/api/';
    this.listDistinct = function(table, field){
        return $http({
            method: 'post'
            , url: base + '/list-distinct.php'
            , params: {
                table: table
                , field: field
            }
        });
    }
});
控制器将注入服务并调用访问api所需的任何方法。结果将通过附加承诺回调以相同的方式获得

.controller('ListCtrl', function($scope, APIService){
    APIService.listDistinct('customer', 'cust_code').then(function(data){
        $scope.data = data;
    })
});
对于代码的PHP端,您需要使用可能的表/字段名的白名单,以确保安全操作。如果没有这样的检查,您很容易受到SQL注入攻击。一个简单的数组检查就足够了

$safeTables = ['customer', 'supplier'];
$safeFields = ['cust_code', 'supp_code'];

if (!in_array($tablename, $safeTables) || !in_array($fieldname, $safeFields)){
   throw new Exception('Invalid parameter');
}

您可以创建一个包含访问API方法的服务。这将使您能够减少控制器中的代码重复,并允许更干净的代码

.service('APIService', function($http){
    var base = 'http://localhost/api/';
    this.listDistinct = function(table, field){
        return $http({
            method: 'post'
            , url: base + '/list-distinct.php'
            , params: {
                table: table
                , field: field
            }
        });
    }
});
控制器将注入服务并调用访问api所需的任何方法。结果将通过附加承诺回调以相同的方式获得

.controller('ListCtrl', function($scope, APIService){
    APIService.listDistinct('customer', 'cust_code').then(function(data){
        $scope.data = data;
    })
});
对于代码的PHP端,您需要使用可能的表/字段名的白名单,以确保安全操作。如果没有这样的检查,您很容易受到SQL注入攻击。一个简单的数组检查就足够了

$safeTables = ['customer', 'supplier'];
$safeFields = ['cust_code', 'supp_code'];

if (!in_array($tablename, $safeTables) || !in_array($fieldname, $safeFields)){
   throw new Exception('Invalid parameter');
}

也许可以创建一个API
服务
,这样你就不会有重复的代码。你的问题是什么?Cleaner JS或PHP?您不应该将GET参数直接解析到SQL查询中。尤其不适用于
字段
/
。这是一种很大的安全滞后@lin是通过添加
mysqli\u real\u escape\u string
来实现的吗?也许可以创建一个API
服务
,这样您就不会有重复的代码您的问题是什么?Cleaner JS或PHP?您不应该将GET参数直接解析到SQL查询中。尤其不适用于
字段
/
。这是一种很大的安全滞后@lin是通过添加
mysqli\u real\u escape\u string
来实现的吗?这是否意味着我仍然需要创建多个控制器,例如,1个用于客户,1个用于供应商?不,您可以使用一个控制器,只需将必要的信息作为参数传递到服务中即可。抱歉,仍然不太清楚,我有一个带有
div
的html,里面有一个控制器。假设我有第一个
div
,它将显示来自客户的数据,代码将是
,而另一个div将显示来自供应商的数据,使用相同的控制器,它也将是
,在这里我可以传递参数以获得正确的数据。如果在一个页面上进行单独的div,请使用单独的控制器。如果您通过使用路线参数使用ngRoute,则可以使用单个控制器。好的,谢谢您的指导,我将尝试查找ngRoute。这意味着我仍然必须创建多个控制器,例如,1个用于客户,1个用于供应商?否,您可以使用一个控制器,只需将必要的信息作为参数传递到服务中。抱歉,仍然不太清楚,我有一个带有
div
的html,其中包含一个控制器。假设我有第一个
div
,它将显示来自客户的数据,代码将是
,而另一个div将显示来自供应商的数据,使用相同的控制器,它也将是
,在这里我可以传递参数以获得正确的数据。如果在一个页面上进行单独的div,请使用单独的控制器。如果您通过使用路由参数使用ngRoute,则可以使用单个控制器。好的,谢谢您的指导,我将尝试查找ngRoute