在AngularJs POST调用中构造有效负载

时间:2015-06-02 00:50:31

标签: javascript angularjs http

在我的应用程序中,我需要使用以下信息发出POST个请求:

          "data": [
            {
              "type": "Search",
              "thing": "{"Table":"Movie","Field":"Title","Type":"String","Value": "INPUT VALUE GOES HERE"}"
            },
            {
              "type": "Search",
              "thing": "{"Table":"Movie","Field":"Director","Type":"String","Value": "INPUT VALUE GOES HERE"}"
            },
            {
              "type": "Search",
              "thing": "{"Table":"Movie","Field":"Year","Type":"String","Value": "INPUT VALUE GOES HERE"}"
            }
          ]

我的指令只是输入元素,可以将数据放在“INPUT VALUE GOES HERE”点。

我的问题是,我是否可以将所有这些信息预先添加到我的指令的ng-model中,以便在我提交POST请求时,我可以执行以下操作:

function submitRequest(input){    
   var dataToSend = [ input.movieTitle, input.movieDirector, input.movieYear];            
   return $http({
       method: 'POST',
       data: dataToSend    
      }) 
   }

输入是一个$scope变量,用于保存由所有三个不同指令

收集的表单数据

我只是不确定如何构建像这样的长查询字符串。

2 个答案:

答案 0 :(得分:0)

您可以将dataToSend设置为该数据数组,并将值设置为适当的输入值。请参阅以下代码:

function submitRequest(input){
   var dataToSend = [
      {
        "type": "Search",
        "thing": "{"Table":"Movie","Field":"Title","Type":"String","Value": input.movieTitle}"
      },
      {
        "type": "Search",
        "thing": "{"Table":"Movie","Field":"Director","Type":"String","Value": input.movieDirector}"
      },
      {
        "type": "Search",
        "thing": "{"Table":"Movie","Field":"Year","Type":"String","Value": input.movieYear}"
      }
    ];
   return $http({
       method: 'POST',
       data: dataToSend
      })
   }

答案 1 :(得分:0)

所以我最终做了rkho建议并做了这件事:

var query = {
  requestId: "xxxx",
  method: "search",
  include: "title, director, year"
}
function submitRequest(data) {
  query.data = [];
  for(var i = 0; i < data.length; i++) {
    var queryData = {
      data: {
        table: data[i].table || "default",
        field: data[i].field || "default",
        type: data[i].type || "default",
        value: data[i].value
      }
    }
    queryData["data"] = angular.toJson(queryData["data"]);
    query.data.push(queryData);
  }
  return $http({
    method: 'POST',
    url: 'URL GOES HERE',
    data: query
  })
}

这样,它会更有活力。