2017-02-16 36 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": "" 
} 

我希望有人認爲它很有用