2017-02-16 71 views
0

目前我已经在你发送一个JSON和API响应的API: 的JSON我送:{ "instructions": [ { "A": 9, "B": 1, "move": "moveonto" }, { "A": 8, "B": 1, "move": "moveover" } ], "length": 20, "res": "null" }建筑JSON字符串的形式

和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" }

IM发展非常基本的网页: 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; 
    }); 

非常感谢你为你的时间,通过它的所有阅读。

+0

你会得到任何错误? – Coder

回答

0

你不一定要“建立”典型意义上的json。通过发送对象数据,angularjs将它转换为json给你。例如

。如果我有一个这样的JavaScript变量:

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

和在HTTP POST发送它作为数据时,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; 
      }); 

    }) 

而且,你不需要引用键值。它的隐含的

综上所述,验证数据包在开发人员工具中正确构建。

0

通读计算器,我发现这个:

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

,所以我建矿用:

//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] 
      }) 
     } 

结果JSON是这样的:

{ 
    "instructions": [ 
     { 
      "A": 1 
      , "B": 3, 
      "move": 
      "moveonto" 
     }, 
     { 
      "A": 5, 
      "B": 9, 
      "move": "pileover" 
     } 
     ], 
     "length": 22, 
     "res": "" 
} 

我希望有人认为它很有用