简体   繁体   English

Angular JS和AJAX发布数据无法正常工作

[英]Angular JS and AJAX posting data doesn't work first click

I focus on Angular JS and I try to posting data with AJAX in ANGULARJS it's working but not first time. 我专注于Angular JS,我尝试在ANGULARJS中使用AJAX发布数据,但它尚可,但不是第一次。

In my html button has ng-click="check()" 在我的html按钮中有ng-click =“ check()”

This is my app.js code. 这是我的app.js代码。

    var app=angular.module("app",[]);
app.controller("control",function($scope){

    $scope.check=function (){
    var mesaj = {
        content: $scope.content,
        flag:"message"
    }
    $.ajax(
    {
        type: 'POST',
        url: 'send.php',
        data: {query: mesaj},
        success: function (result)
        {
            $scope.result=result;
        }
    });
    }
});

and my send.php is taking data(content) after that echo $content 我的send.php在回显$ content之后获取数据(内容)

I have double click to button for working AJAX but I want to work at first time 我需要双击以使用AJAX,但是我想在第一次使用

Since you're not using the http service, 由于您没有使用http服务,

you need to tell angular that variables were modified. 您需要告诉angular变量已修改。

by doing $scope.$apply() after your success. 在成功之后执行$scope.$apply()

var app=angular.module("app",[]);
app.controller("control",function($scope){

    $scope.check=function (){
    var mesaj = {
        content: $scope.content,
        flag:"message"
    }
    $.ajax(
    {
        type: 'POST',
        url: 'send.php',
        data: {query: mesaj},
        success: function (result)
        {
            $scope.result=result;
            $scope.$apply()
        }
    });
    }
});

Inject $http and call a post, it follows better convention when using angular for posting data: 注入$ http并调用一个帖子,使用angular来发布数据时遵循更好的约定:

 function sendMesaj() {

         $http.post('send.php', mesaj)
            .then(function(result){

                $scope.result=result;

            }, handleError);

        function handleError(response){
            return response;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM