从表单角度构建JSON字符串

时间:2017-02-16 19:02:14

标签: angularjs json post build

目前我有一个api,你发送一个json和api响应: 我发送的json:{ "instructions": [ { "A": 9, "B": 1, "move": "moveonto" }, { "A": 8, "B": 1, "move": "moveover" } ], "length": 20, "res": "null" }

和api回复:{ "instructions": [ { "A": 9, "B": 1, "move": "moveonto" }, { "A": 8, "B": 1, "move": "moveover" } ], "length": 20, "res": "Position [0] : 0Position [1] : 1 9 8Position [2] : 2Position [3] : 3Position [4] : 4Position [5] : 5Position [6] : 6Position [7] : 7Position [8] : Position [9] : Position [10] : 10Position [11] : 11Position [12] : 12Position [13] : 13Position [14] : 14Position [15] : 15Position [16] : 16Position [17] : 17Position [18] : 18Position [19] : 19" }

我正在开发一个非常基本的网页: My Webpage 当我点击发送到服务器按钮我需要发送它,问题是我不知道如何建立json,你能帮帮我吗? THX

我有点想法:

Json = {
  "instructions": [{
    "A": $scope.addA,
    "B": $scope.addB,
    "move": $scope.addMov
  }, {
    "A": $scope.addA,
    "B": $scope.addB,
    "move": $scope.addMov
  }],
  "length": $scope.blockLength,
  "res": null
};

我寄给你:

$http.post("http://localhost:56493/api/BlocksProblem", Json)
  .then(function (data) {
    $scope.result = data;
  }, function (response) {
    $scope.result = response;
  });

非常感谢您抽出时间阅读所有内容。

2 个答案:

答案 0 :(得分:0)

你不一定"建立"典型意义上的json。通过发送对象数据,angularjs将其转换为json。

例如,

。如果我有这样的javascript变量:

var J = {A:1, B:2} 

并将其作为数据发送到http帖子中,json看起来像: {" A":" 1"" B":" 2"}

如果没有看到您的服务器架构的样子,您可以做类似的事情

 $scope.SendJson = function (Callback) {

    $http({
        url: YOURURL,
        method: 'POST',
        dataType: 'json',
        data: {
          "instructions": [
                 {"A": $scope.addA,"B": $scope.addB,"move": $scope.addMov}, 
                 {"A": $scope.addA,"B": $scope.addB,"move": $scope.addMov}],
          "length": $scope.blockLength,
          "res": null}
     })
     .then(function (data) {
               $scope.result = data;
            }, function (response) {
                 $scope.result = response;
            });

    })

此外,您不需要引用键值。其含蓄

尽管如此,请验证数据包是否在开发人员工具中正确构建。

答案 1 :(得分:0)

通过stackoverflow读取我发现了这个:

How do I create JavaScript array (JSON format) dynamically?

所以我建立了我的:

ls

结果json类似于:

    //here i save the values of A,B and the moves, that i get from the form 
    var serverMove = [];
    var serverA = [];
    var serverB = [];
    //create the json 
    var jsonS = {
          instructions: [],
          "length": $scope.blockLength,
          "res": ""
    };
       //dynamically  fill only the instrucions array part 
        for (var i = 0; i < serverA.length; i++) {
          jsonS.instructions.push({
            "A": serverA[i],
            "B": serverB[i],
            "move": serverMove[i]
          })
        }

我希望有人觉得它很有用