Im using Angular with pure JS. I have an array like this:
arr = [1, 2, 5, 32];
But I need to POST this to an API in JSON. I'm trying to achieve this:
{'reportIDs': [1, 2, 5, 32]}
Is there an easy way to do this in Angular?
Wherever it is that you need this value, you can create that object almost exactly as in your question:
var obj = {'reportIDs': arr};
You don't need the '
, but they don't do any harm.
But if you really need to send JSON , your example isn't JSON. In JSON, property names must be in double quotes. The simplest way to create valid JSON is to use JSON.stringify
:
var json = JSON.stringify({reportIDs:arr});
If you're sending that somewhere, you'd use that value as the data
in a $http
call.
You might want to use angular.toJson
instead of using JSON.stringify
directly, as it skips some internal Angular prooperties.
You need to sent an Ajax request to the server
If you want to keep the json code, insert it as a string
$http.post("the_url_to_sent_data",
{'json' : JSON.stringify({'reportIDs': arr})}
).then(function (response) {
// Hey, i got a responce
return response;
});
Then get the json parameter's value and parse it.
Or just send the data and let the library parse them
$http.post("the_url_to_sent_data",
{'reportIDs': arr}
).then(function (response) {
// Hey, i got a responce
return response;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.