AngularJS通过阵列形式到PHP [英] AngularJS pass form array to php

查看:166
本文介绍了AngularJS通过阵列形式到PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我努力让这种形式的工作想知道如果任何人都可以给我任何想法,为什么!所以我有一个索引页与NG-应用=特殊。在DIV main_area_holder那张ng_view。在吴视图显示索引页(从当前位置应用程序/谐音/ cust_form.php)的罚款和形式显示。我所努力让工作是HTTP请求到PHP文件,所以我可以导入表单数据到数据库。我知道没有Ajax(直POST请求)的PHP code ++工程。如果你能帮忙我将非常感激。

app.js更新时间:

  VAR特殊= angular.module('特殊',['ngRoute']);

especial.config(函数($ routeProvider){
$ routeProvider.when('/',
    {
        控制器:custPage,
        templateUrl:应用程序/谐音/ cust_form.tpl.html
    });
});

especial.config(函数($ httpProvider){
$ httpProvider.defaults.transformRequest =功能(要求){
    如果(typeof运算(要求)!='对象'){
        返回请求;
    }
    VAR海峡= [];
    为(在要求VAR K){
        如果(k.charAt(0)=='$'){
            删除请求[k]的;
            继续;
        }
        VAR V ='对象'== typeof运算(要求[K])JSON.stringify(要求[K]):要求[K]
        str.push(EN codeURIComponent(K)+=+ EN codeURIComponent(V));
    }
    返回str.join(与&);
};
$ httpProvider.defaults.timeout = 10000;
$ httpProvider.defaults.headers.post = {
    内容类型:应用程序/ x-WWW的形式urlen codeD',
    X-要求,以:XMLHtt prequest
};
});
especial.controller('custPage',函数($范围,$ HTTP){
    $范围= {};
    $ scope.custCreUpd =功能(){
        $ HTTP({
            方法:POST,
            网址:应用程序/ PHP / cust_cre_upd.php',
            数据:$ scope.cust,
            标题:{内容类型:应用程序/ x-WWW的形式urlen codeD'}
        }),成功(功能(数据){

            的console.log(OK,数据)

        })错误(功能(错误){ERR,执行console.log(ERR)})
    };
});
 

cust_cre_upd.php

 < PHP

        $ =后的file_get_contents(PHP://输入);
        $值= json_de code($后,真正的);
        $表='客户';
        $康恩=新PDO('mysql的:主机=本地主机,数据库名= displaytrends;字符集= UTF8','displaytrends','displaytrends');
        $ conn->的setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION);
                    //地带数组的字段,其值
        $值= array_filter($值);
                    //以从数组的数组键
        $ field_keys = array_keys($值);
                    //内爆的刀片领域
        $ ins_fields =破灭(,,$ field_keys);
                    //内爆的插入值字段(值会在以后绑定)
        $ value_fields =:。破灭(:,$ field_keys);
                    //创建为每个阵列更新的领域创造价值=价值=:值。
        $ update_fields = array_keys($值);
        的foreach($ update_fields为&放大器; $ VAL){
            $ VAL = $ VAL=。$ VAL;
        }
        $ update_fields =破灭(,,$ update_fields);
                    // SQL查询
        $插入=INSERT INTO $表($ ins_fields)VALUES($ value_fields)对重复密钥更新$ update_fields;
        $查询= $ conn-> prepare($插入);
                    //绑定的基础上的价值未来的每个值。
        的foreach($值$关键=>&安培; $值){
            开关(的GetType($值)){
                案整数:
                情况下双师型:
                $查询 - > bindParam(':'$关键,$值,PDO :: PARAM_INT);
                打破;
                默认:
                $查询 - > bindParam(':'$关键,$值,PDO :: PARAM_STR);
            }
        }
        $查询 - >执行();

    ?>
 

的index.php

 <!DOCTYPE HTML>
< HTML NG-应用程序=特殊>
< HEAD>
<元的charset =UTF-8>
<冠军>贝斯 - 数据库< /标题>
<链接相对=样式表的href =CSS / index.css>
<脚本SRC =脚本/ angular.js>< / SCRIPT>
<脚本SRC =脚本/角route.js>< / SCRIPT>
<脚本SRC =脚本/角animate.js>< / SCRIPT>
< /头>

<身体GT;
< D​​IV CLASS =标头>
< IMG ID =标志SRC =图像/特殊-logo.jpg>
&其中;一的id =登出的href =logout.php>注销&所述; / a取代;
< D​​IV CLASS =菜单>< / DIV>
< / DIV>
< D​​IV CLASS =sub_menu>< / DIV>

< D​​IV CLASS =main_area>
    < D​​IV ID =main_area_holderNG-视图>
    < / DIV>
< / DIV>
< D​​IV CLASS =页脚>< / DIV>
<脚本SRC =应用程序/ app.js>< / SCRIPT>
< /身体GT;
< / HTML>
 

cust_form.php

 < D​​IV NG控制器=custPage>
< D​​IV ID =形式>
        <表格名称=cust_form>
           <标签>帐号:< /标签>
           <输入类型=文本NG-模式=cust.int_custIDNAME =卡斯特[int_custID]ID =int_custID/>
           <标签>公司:其中; /标签>
           <输入类型=文本NG-模式=cust.cust_companyNAME =卡斯特[cust_company]ID =cust_company/>
            <标签>地址:< /标签>
            < textarea的类型=文本行数= 5纳克模型=cust.cust_addressNAME =卡斯特[cust_address]ID =cust_address>< / textarea的>
            <标签>后code:< /标签>
            <输入类型=文本NG-模式=cust.cust_post codeNAME =卡斯特[cust_post code]ID =cust_post code/>
            <标签>联系1:< /标签>
            <输入类型=文本NG-模式=cust.cust_contact_1NAME =卡斯特[cust_contact_1]ID =cust_contact_1/>
            <标签>联系方式2:其中; /标签>
            <输入类型=文本NG-模式=cust.cust_contact_2NAME =卡斯特[cust_contact_2]ID =cust_contact_2/>
            <标签>联系电话:< /标签>
            <输入类型=文本NG-模式=cust.cust_telNAME =卡斯特[cust_tel]ID =cust_tel/>
            <标签>手机:< /标签>
            <输入类型=文本NG-模式=cust.cust_mobNAME =卡斯特[cust_mob]ID =cust_mob/>
            <标签> DDI:LT; /标签>
            <输入类型=文本NG-模式=cust.cust_DDINAME =卡斯特[cust_DDI]ID =cust_DDI/>
            <标签>电子邮件:LT; /标签>
            <输入类型=电子邮件NG-模式=cust.cust_emailNAME =卡斯特[CUST_EMAIL]ID =CUST_EMAIL/>
            <标签>注意:< /标签>
            < textarea的类型=文本行数= 5 colums = 1纳克模型=cust.cust_notesNAME =卡斯特[cust_notes]ID =cust_notes>< / textarea的>

           <按钮类型=提交NG点击=custCreUpd()>提交< /按钮>
       < /形式GT;
< / DIV>
< / DIV>
 

解决方案

app.js:

  VAR特殊= angular.module('特殊',['ngRoute']);

especial.config(函数($ routeProvider){
    $ routeProvider.when('/',
    {
        控制器:custPage,
        templateUrl:应用程序/谐音/ cust_form.tpl.html
    });
});

especial.config(函数($ httpProvider){
$ httpProvider.defaults.transformRequest =功能(要求){
    如果(typeof运算(要求)!='对象'){
        返回请求;
    }
    VAR海峡= [];
    为(在要求VAR K){
        如果(k.charAt(0)=='$'){
            删除请求[k]的;
            继续;
        }
        VAR V ='对象'== typeof运算(要求[K])JSON.stringify(要求[K]):要求[K]
        str.push(EN codeURIComponent(K)+=+ EN codeURIComponent(V));
    }
    返回str.join(与&);
};
$ httpProvider.defaults.timeout = 10000;
$ httpProvider.defaults.headers.post = {
    内容类型:应用程序/ x-WWW的形式urlen codeD',
    X-要求,以:XMLHtt prequest
};
});
especial.controller('custPage',函数($范围,$ HTTP){
   $ scope.cust = {};
   $ scope.custCreUpd =功能(){
    $ HTTP({
        方法:POST,
        网址:应用程序/ PHP / cust_cre_upd.php',
        数据:$ scope.cust,
        标题:{内容类型:应用程序/ x-WWW的形式urlen codeD'}
    }),成功(功能(数据){
        的console.log(数据)
    })错误(功能(错误){
        执行console.log(ERR)
    })
};
});
 

cust_cre_upd.php

 < PHP
//的print_r($ _ POST);你可以的print_r它理解
//使用$ _ POST和往常一样,例如$ _ POST [CUST_ID]是指你
$值= $ _ POST;
$康恩=新PDO('mysql的:主机=本地主机,数据库名= displaytrends;字符集= UTF8','displaytrends','displaytrends');
$ conn->的setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION);
//地带数组的字段,其值
$值= array_filter($值);
//以从数组的数组键
$ field_keys = array_keys($值);
//内爆的刀片领域
$ ins_fields =破灭(,,$ field_keys);
//内爆的插入值字段(值会在以后绑定)
$ value_fields =:。破灭(:,$ field_keys);
//创建为每个阵列更新的领域创造价值=价值=:值。
$ update_fields = array_keys($值);
的foreach($ update_fields为&放大器; $ VAL){
    $ VAL = $ VAL=。$ VAL;
}
$ update_fields =破灭(,,$ update_fields);
// SQL查询
$插入=INSERT INTO $表($ ins_fields)VALUES($ value_fields)对重复密钥更新$ update_fields;
$查询= $ conn-> prepare($插入);
//绑定的基础上的价值未来的每个值。
的foreach($值$关键=>&安培; $值){
    开关(的GetType($值)){
        案整数:
        情况下双师型:
            $查询 - > bindParam(':'$关键,$值,PDO :: PARAM_INT);
            打破;
        默认:
            $查询 - > bindParam(':'$关键,$值,PDO :: PARAM_STR);
    }
}
$查询 - >执行();
 

的index.php:

 <!DOCTYPE HTML>
< HTML NG-应用程序=特殊>
< HEAD>
    <元的charset =UTF-8>
    <冠军>贝斯 - 数据库< /标题>
<! - <链接相对=样式表的href =CSS / index.css>  - >
    <脚本SRC =脚本/角1.3.8.min.js>< / SCRIPT>
    <脚本SRC =脚本/角route.min.js>< / SCRIPT>
&所述;! - &所述;脚本的src =脚本/角animate.js>&所述; /脚本&GT  - →;
< /头>

<身体GT;
< D​​IV CLASS =标头>
    < IMG ID =标志SRC =图像/特殊-logo.jpg>
    &其中;一的id =登出的href =logout.php>注销&所述; / a取代;
    < D​​IV CLASS =菜单>< / DIV>
< / DIV>
< D​​IV CLASS =sub_menu>< / DIV>

< D​​IV CLASS =main_area>
    < D​​IV ID =main_area_holderNG-视图>
    < / DIV>
< / DIV>
< D​​IV CLASS =页脚>< / DIV>
<脚本SRC =应用程序/ app.js>< / SCRIPT>
< /身体GT;
< / HTML>
 

cust_form.php(cust_form.tpl.html):

 < D​​IV ID =形式>
    <表格名称=cust_form>
        <标签>帐号:< /标签>
        <输入类型=文本NG-模式=cust.int_custIDID =int_custID/>
        <标签>公司:其中; /标签>
        <输入类型=文本NG-模式=cust.cust_companyID =cust_company/>
        <标签>地址:< /标签>
        < textarea的类型=文本行数= 5纳克模型=cust.cust_addressID =cust_address>< / textarea的>
        <标签>后code:< /标签>
        <输入类型=文本NG-模式=cust.cust_post codeID =cust_post code/>
        <标签>联系1:< /标签>
        <输入类型=文本NG-模式=cust.cust_contact_1ID =cust_contact_1/>
        <标签>联系方式2:其中; /标签>
        <输入类型=文本NG-模式=cust.cust_contact_2ID =cust_contact_2/>
        <标签>联系电话:< /标签>
        <输入类型=文本NG-模式=cust.cust_telID =cust_tel/>
        <标签>手机:< /标签>
        <输入类型=文本NG-模式=cust.cust_mobID =cust_mob/>
        <标签> DDI:LT; /标签>
        <输入类型=文本NG-模式=cust.cust_DDIID =cust_DDI/>
        <标签>电子邮件:LT; /标签>
        <输入类型=电子邮件NG-模式=cust.cust_emailID =CUST_EMAIL/>
        <标签>注意:< /标签>
        < textarea的类型=文本行数= 5 colums = 1纳克模型=cust.cust_notesID =cust_notes>< / textarea的>

        <按钮类型=提交NG点击=custCreUpd()>提交< /按钮>
    < /形式GT;
< / DIV>
 

我创造一个仓库在这里 https://github.com/Danzeer/forJoshCrocker

要在Web浏览器的脚本调试,你可以使用Chrome的开发人员工具 - 网络(选项+命令+我在OSX,F12在窗口,选择网卡)。当你点击提交,就可以看到在网络请求卡并通过单击请求检查HTTP标头。

I am struggling to get this form to work was wondering if anyone can give me any ideas why! So what I have is an index page with an ng-app=especial. In the DIV main_area_holder goes the ng_view. The Ng-view displays fine and form displays on index page (from localtion app/partials/cust_form.php). What I am struggling to get working is the http request to php file so I can import form data into DB. I know the php code works without ajax (straight post request). If you can help out I would be very grateful.

app.js UPDATED

var especial = angular.module('especial', ['ngRoute']);

especial.config(function($routeProvider) {
$routeProvider.when('/',
    {
        controller: 'custPage',
        templateUrl: 'app/partials/cust_form.tpl.html'
    });
});

especial.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(request){
    if(typeof(request)!='object'){
        return request;
    }
    var str = [];
    for(var k in request){
        if(k.charAt(0)=='$'){
            delete request[k];
            continue;
        }
        var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
        str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
    return str.join("&");
};
$httpProvider.defaults.timeout=10000;
$httpProvider.defaults.headers.post = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'X-Requested-With': 'XMLHttpRequest'
};
});
especial.controller('custPage', function($scope, $http){
    $scope = {};
    $scope.custCreUpd = function(){
        $http({
            method: 'POST',
            url: 'app/php/cust_cre_upd.php',
            data: $scope.cust,
            headers : {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function(data){

            console.log("OK", data)

        }).error(function(err){"ERR", console.log(err)})
    };
});

cust_cre_upd.php

<?php

        $post = file_get_contents("php://input");
        $values = json_decode($post, true);
        $table='customers';
        $conn = new PDO('mysql:host=localhost;dbname=displaytrends;charset=utf8', 'displaytrends', 'displaytrends');
        $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                    //Strip array to fields with values     
        $values=array_filter($values);
                    //Take array keys from array
        $field_keys=array_keys($values);
                    //Implode for insert fields
        $ins_fields=implode(",", $field_keys);
                    //Implode for insert value fields (values will binded later)
        $value_fields=":" . implode(", :", $field_keys);
                    //Create update fields for each array create value = 'value = :value'.
        $update_fields=array_keys($values);
        foreach($update_fields as &$val){
            $val=$val." = :".$val;
        }
        $update_fields=implode(", ", $update_fields);
                    //SQL Query
        $insert = "INSERT INTO $table ($ins_fields) VALUES ($value_fields) ON DUPLICATE KEY UPDATE $update_fields";
        $query = $conn->prepare($insert);
                    //Bind each value based on value coming in.
        foreach ($values as $key => &$value) {
            switch(gettype($value)) {
                case 'integer':
                case 'double':
                $query->bindParam(':' . $key, $value, PDO::PARAM_INT);
                break;
                default:
                $query->bindParam(':' . $key, $value, PDO::PARAM_STR);
            }
        }
        $query->execute();

    ?>

index.php

<!doctype html>
<html ng-app="especial">
<head>
<meta charset="UTF-8">
<title>Especial - Database</title>
<link rel="stylesheet" href="css/index.css">
<script src="scripts/angular.js"></script>
<script src="scripts/angular-route.js"></script>
<script src="scripts/angular-animate.js"></script>
</head>

<body>
<div class="header">
<img id="logo" src="images/especial-logo.jpg">
<a id="logout" href="logout.php">Logout</a>
<div class="menu"></div>
</div>
<div class="sub_menu"></div>

<div class="main_area">
    <div id="main_area_holder" ng-view>
    </div>
</div>
<div class="footer"></div>
<script src="app/app.js"></script>
</body>
</html>

cust_form.php

<div ng-controller="custPage">
<div id="form">
        <form name="cust_form">   
           <label>Account No:</label>
           <input type="text" ng-model="cust.int_custID" name="cust[int_custID]" id="int_custID"/>
           <label>Company:</label>
           <input type="text" ng-model="cust.cust_company" name="cust[cust_company]" id="cust_company"/>
            <label>Address:</label>
            <textarea type="text" rows=5 ng-model="cust.cust_address" name="cust[cust_address]" id="cust_address"></textarea>
            <label>Postcode:</label>
            <input type="text" ng-model="cust.cust_postcode" name="cust[cust_postcode]" id="cust_postcode"/>
            <label>Contact 1:</label>
            <input type="text" ng-model="cust.cust_contact_1" name="cust[cust_contact_1]" id="cust_contact_1"/>
            <label>Contact 2:</label>
            <input type="text" ng-model="cust.cust_contact_2"  name="cust[cust_contact_2]"  id="cust_contact_2"/>
            <label>Telephone:</label>
            <input type="text" ng-model="cust.cust_tel" name="cust[cust_tel]" id="cust_tel"/>
            <label>Mobile:</label>
            <input type="text" ng-model="cust.cust_mob" name="cust[cust_mob]" id="cust_mob"/>
            <label>DDI:</label>
            <input type="text" ng-model="cust.cust_DDI" name="cust[cust_DDI]" id="cust_DDI"/>
            <label>Email:</label>
            <input type="email" ng-model="cust.cust_email" name="cust[cust_email]" id="cust_email"/>
            <label>Notes:</label>
            <textarea type="text" rows=5 colums=1 ng-model="cust.cust_notes"  name="cust[cust_notes]" id="cust_notes"></textarea>

           <button type="submit" ng-click="custCreUpd()"> Submit </button>
       </form>
</div>
</div>

解决方案

app.js:

var especial = angular.module('especial', ['ngRoute']);

especial.config(function($routeProvider) {
    $routeProvider.when('/',
    {
        controller: 'custPage',
        templateUrl: 'app/partials/cust_form.tpl.html'
    });
});

especial.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(request){
    if(typeof(request)!='object'){
        return request;
    }
    var str = [];
    for(var k in request){
        if(k.charAt(0)=='$'){
            delete request[k];
            continue;
        }
        var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
        str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
    return str.join("&");
};
$httpProvider.defaults.timeout=10000;
$httpProvider.defaults.headers.post = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'X-Requested-With': 'XMLHttpRequest'
};
});
especial.controller('custPage', function($scope, $http){
   $scope.cust = {};
   $scope.custCreUpd = function(){
    $http({
        method: 'POST',
        url: 'app/php/cust_cre_upd.php',
        data: $scope.cust,
        headers : {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data){
        console.log(data)
    }).error(function(err){
        console.log(err)
    })
};
});

cust_cre_upd.php

<?php
//print_r($_POST); you can print_r it for understanding
//use $_POST as usual, example $_POST["cust_ID"] means your     
$values = $_POST;
$conn = new PDO('mysql:host=localhost;dbname=displaytrends;charset=utf8', 'displaytrends', 'displaytrends');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Strip array to fields with values
$values=array_filter($values);
//Take array keys from array
$field_keys=array_keys($values);
//Implode for insert fields
$ins_fields=implode(",", $field_keys);
//Implode for insert value fields (values will binded later)
$value_fields=":" . implode(", :", $field_keys);
//Create update fields for each array create value = 'value = :value'.
$update_fields=array_keys($values);
foreach($update_fields as &$val){
    $val=$val." = :".$val;
}
$update_fields=implode(", ", $update_fields);
//SQL Query
$insert = "INSERT INTO $table ($ins_fields) VALUES ($value_fields) ON DUPLICATE KEY UPDATE $update_fields";
$query = $conn->prepare($insert);
//Bind each value based on value coming in.
foreach ($values as $key => &$value) {
    switch(gettype($value)) {
        case 'integer':
        case 'double':
            $query->bindParam(':' . $key, $value, PDO::PARAM_INT);
            break;
        default:
            $query->bindParam(':' . $key, $value, PDO::PARAM_STR);
    }
}
$query->execute();

index.php:

<!doctype html>
<html ng-app="especial">
<head>
    <meta charset="UTF-8">
    <title>Especial - Database</title>
<!--    <link rel="stylesheet" href="css/index.css">-->
    <script src="scripts/angular-1.3.8.min.js"></script>
    <script src="scripts/angular-route.min.js"></script>
<!--    <script src="scripts/angular-animate.js"></script>-->
</head>

<body>
<div class="header">
    <img id="logo" src="images/especial-logo.jpg">
    <a id="logout" href="logout.php">Logout</a>
    <div class="menu"></div>
</div>
<div class="sub_menu"></div>

<div class="main_area">
    <div id="main_area_holder" ng-view>
    </div>
</div>
<div class="footer"></div>
<script src="app/app.js"></script>
</body>
</html>

cust_form.php (cust_form.tpl.html):

<div id="form">
    <form name="cust_form">
        <label>Account No:</label>
        <input type="text" ng-model="cust.int_custID" id="int_custID"/>
        <label>Company:</label>
        <input type="text" ng-model="cust.cust_company"  id="cust_company"/>
        <label>Address:</label>
        <textarea type="text" rows=5 ng-model="cust.cust_address" id="cust_address"></textarea>
        <label>Postcode:</label>
        <input type="text" ng-model="cust.cust_postcode" id="cust_postcode"/>
        <label>Contact 1:</label>
        <input type="text" ng-model="cust.cust_contact_1"  id="cust_contact_1"/>
        <label>Contact 2:</label>
        <input type="text" ng-model="cust.cust_contact_2"  id="cust_contact_2"/>
        <label>Telephone:</label>
        <input type="text" ng-model="cust.cust_tel" id="cust_tel"/>
        <label>Mobile:</label>
        <input type="text" ng-model="cust.cust_mob" id="cust_mob"/>
        <label>DDI:</label>
        <input type="text" ng-model="cust.cust_DDI" id="cust_DDI"/>
        <label>Email:</label>
        <input type="email" ng-model="cust.cust_email" id="cust_email"/>
        <label>Notes:</label>
        <textarea type="text" rows=5 colums=1 ng-model="cust.cust_notes" id="cust_notes"></textarea>

        <button type="submit" ng-click="custCreUpd()"> Submit </button>
    </form>
</div>

I creat a repository here https://github.com/Danzeer/forJoshCrocker

To debug with script in web browser, you can use chrome's Developer's tools - network (option+command+i in OSX, F12 in window, and chose the network card).When you click submit, you can see request in network card and check http header by clicking the request.

这篇关于AngularJS通过阵列形式到PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆