【问题标题】:Can not display the success message after submit data using angular.js and php使用angular.js和php提交数据后无法显示成功消息
【发布时间】:2015-10-01 09:02:18
【问题描述】:

使用 Angular.js 和 PHP 提交数据后,我无法显示成功消息。我正在使用警报提示来显示消息,但它显示输出为undefined。我在下面解释我的代码。

createSubjectData.php:

<?php
$course_name=stripslashes($_POST['course_name']);
$sub_name=stripslashes($_POST['sub_name']);
$semester=stripslashes($_POST['semester']);
$sub_short_name=stripslashes($_POST['sub_short_name']);
$con = mysql_connect('localhost', 'root', '******');
mysql_select_db('go_fasto', $con);
 $qry ='INSERT INTO db_subject (subject_name,short_name,semester,course_name) values ("' . $sub_name . '","' . $sub_short_name . '","' . $semester . '","' .$course_name . '")';
$qry_res = mysql_query($qry);
if ($qry_res){
        $result['msg'] = "subject has added successfully";
    } else {
         $result['msg'] =  "subject could not added ";
    }
$query='SELECT * from db_subject order by subject_id desc';
$res=mysql_query($query);
$result=mysql_fetch_array($res);
echo json_encode($result);
?>

我的控制器代码如下。

var subjectData={'course_name':$scope.courseName.value,'semester':$scope.semester.value,'sub_short_name':$scope.subject_short_name,'sub_name':$scope.subjectname};
                console.log('subject',subjectData)
                $.ajax({
                    method: 'POST',
                    url: "php/subject/createSubjectData.php",
                    data: subjectData,
                    dataType: 'json',
                    success: function(response){
                        $scope.$apply(function(){
                        alert(response.msg);
                        $scope.courseName=null;
                        $scope.semester=null;
                        $scope.subject_short_name=null;
                        $scope.subjectname=null;
                        //$scope.subjectData.push(response);
                        $scope.subjectData.unshift(response);
                        });
                    },
                    error: function(response){
                        alert(response.msg);
                    }
                })

请帮我解决这个问题。

【问题讨论】:

  • 我一直在想,你为什么用jQuery的$.ajax()。你确实意识到你可以使用 Angular 的 $http 对吗?
  • 是的,我知道,但它只是我的演示代码。我仅用于测试。在这种情况下你能帮我吗
  • 好吧,因为response.msg 不存在,所以你得到了未定义。
  • 检查我的 php 文件,我正在传递消息,它将返回成功消息。

标签: javascript php angularjs


【解决方案1】:

您将在这一行中完全覆盖您的 $result 变量

$result=mysql_fetch_array($res);

你设置了$result['msg']="...",所以消息丢失了。

顺便说一句: 您的代码中存在 SQL 注入问题。在将输入变量添加到查询字符串或用户 mysql prepared statements mysqli_stmt之前,使用 mysql_real_escape_string() 清理输入变量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    相关资源
    最近更新 更多