在AngularJS中创建JSON字符串

Creating JSON string in AngularJS

本文关键字:JSON 字符串 创建 AngularJS      更新时间:2023-09-26

我想使用AngularJS:创建以下格式的JSON字符串

{
    "userid": 100,
    "fleetid": 506,
    "comments": "This is a test comment",
    "fleetcheckdate": "29/10/1976",
    "options": [{
        "fleetcheckid": "1",
        "fleetcheckvalueid": "1"
    }, {
        "fleetcheckid": "2",
        "fleetcheckvalueid": "1"
    }, {
        "fleetcheckid": "3",
        "fleetcheckvalueid": "1"
    }]
}

何处

  • "userid"
  • "羊毛"
  • "评论"
  • "敲诈日期"

我知道所有独立的值。

对于"options",我有一个多维数组,用于存储我创建的的值:

$scope.selectedRadioArray = [];
$scope.doSomething = function(fleetCheckItemID, fleetCheckID)
{
    $scope.selectedIDS = [fleetCheckItemID, fleetCheckID];
    $scope.selectedRadioArray.push($scope.selectedIDS);
    console.log("Array: " + $scope.selectedRadioArray); // Prints e.g. 4,3,8,6,34,8
}

每当用户与按钮交互时,doSomething()方法就会被触发,这会生成两个值"fleetceckid""fleetceckvalueid"。在上面的例子中,用户已经点击了按钮3次。该按钮可以点击任意次数。

我如何将上面的信息转换为JSON字符串,就像我可以通过$http.post()发送到数据库的例子一样?

通过$http向服务器发送信息时,通常最好使用JSON。不要将其转换为字符串。

只需像这样格式化您的有效载荷:

var payload = {
    userId: $scope.userId,
    /* etc.... */
    options: $scope.optionsArray
};

然后,当发送到服务器时,执行以下操作:

$http.post('path/to/api', payload, { headers: { /* etc... */ }}).then(successCallback).catch(errorCallback);

您可以在$http中使用类似的方法

$http({
        url: uri,
        method: 'post',
        data: angular.toJson(categoria),
        headers: {
            'Authorization': 'Bearer ' + token.data.access_token,
            'Content-type': 'application/json'
        }
    }).then(function successCallback(response) {
        datosRecu = response;
        deferred.resolve(datosRecu);
    }, function errorCallback(response) {
        datosRecu = response;
        deferred.resolve(datosRecu);
    });
in this case `angularToJson` convert it on a JSON and send it in the body