jQuery .serialize()在angular中无法正常工作

时间:2015-12-06 15:49:19

标签: jquery angularjs

我正在以我希望通过jQuery .serialize()函数发布所有字段的形式工作,但是当我提醒我的序列化对象时,它只会警告密钥并且不会显示针对密钥的值。

这是我的角色剧本。

 app.controller('myForm',function($http,$scope){

    $scope.mydata=$('#myform').serialize();

    $scope.saveCashbook=function()
    {
        alert(this.mydata);
      $http({
        method: "POST",
        url: 'cashbook/save_cash_entry',
        data: this.mydata,
      }).success(function (data) {
        if (data.status == 'success') {
          alert('all okay');
        } else {
          alert(data.msg)
        }
      });
    }

 });

在jquery中正常工作

$('#submit').click(function(event) {
    var mydata=$('#myform').serialize();
    alert(mydata);
});

请告诉我我犯错的地方。

3 个答案:

答案 0 :(得分:2)

我使用以下代码完成了...序列化工作对我来说主要的是标题提供信息file <- "bank.csv" data <- read.csv(file, header=TRUE, sep=";") data <- data[(data$Previous_Outcome == "success") | (data$Previous_Outcome == "nonexistent"),] data <- data[(data$Duration != "0"),] age = data$Age duration <- data$Duration png("file1.png") plot(duration~age) abline(lm(duration~age)) dev.off()

headers : { 'Content-Type': 'application/x-www-form-urlencoded' }

答案 1 :(得分:1)

如何使用angular no jQuery发送表单

如果调用需要这样的对象

{
  firstName: "Julian",
  lastName: "Reyes Escrigas"
}

你的html表单就像这样

<form>
  <label for="firstName">First name</label>
  <input type="text" name="firstName" id="firstName" />

  <label for="lastName">Last name</label>
  <input type="text" name="lastName" id="lastName" />

  <input type="submit" value="Process" />
</form>

在你的javascript方面将是类似

function dataController($http) {

  var vm = this;

  vm.myData = {};    

  vm.submit = function() {
    $http({method: 'POST', url: '/endpoint', data: vm.myData})
    .then(/*...*/)
    .catch(/*...*/);
  }
}

app.controller('dataController', ['$http', dataController]);

现在将您的模板更新为此类

<form ng-controller="dataController as ctrl" ng-submit="ctrl.submit()" >
  <label for="firstName">First name</label>
  <input type="text" name="firstName" ng-model="ctrl.myData.firstName" id="firstName" />

  <label for="lastName">Last name</label>
  <input type="text" name="lastName" id="lastName" ng-model="ctrl.myData.lastName"/>

  <input type="submit" value="Process" />
</form>

答案 2 :(得分:1)

使用angular.element(&#39; #myForm&#39;)。serialize();

引自angular.element documentation

  

如果jQuery可用,angular.element是jQuery函数的别名。如果jQuery不可用,angular.element会委托给Angular的内置jQuery子集,称为&#34; jQuery lite&#34;或jqLit​​e。

在审核您的代码后,我想说两件事。

1:始终添加&#34; Ctrl&#34;在您的控制器名称之后,这是在团队中工作时的最佳实践,因为它使您的代码更具可读性。

2:将.success()回调更改为此

.success(function (data) {
      alert(data.msg);
      }
.catch(function(err) {
      alert(err);
      };

原因是因为只有$ http成功才会运行.success()回调。

这意味着if语句没用。

如果发生错误,.catch()会捕获错误。

祝你好运!