问题:
This answer looked pretty close but I think there's a fundamental difference between this answer and my problem that makes the answer insufficient for my needs.
From an a...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
This answer looked pretty close but I think there's a fundamental difference between this answer and my problem that makes the answer insufficient for my needs.
From an ajax post, I'm getting a JSON value returned that looks like this:
{
"token": "wegHOIoi32h4gt834ygli",
"expires": "1496845449"
}
I need to save the token value wegHOIoi32h4gt834ygli
into localStorage.
Here's my code:
$.ajax(settings).done(function (response) {
console.log(response);
$(".Results").html(response);
$.each(response, function (index, element) {
var token = element.value;
console.log(token);
localStorage.setItem("token", token);
})
});
Now I'm getting this error:
Uncaught TypeError: Cannot use 'in' operator to search for '326' in {
"token": "wegHOIoi32h4gt834ygli",
"expires": 1496845449
}
Pretty sure I don't have any idea what's going on at this point. How can I extract the value I'm looking for?
回答1:
Assuming the API response is a string, you'll need to parse it into an object with JSON.parse(responseString)
. This then gives you a plain JavaScript object that you can manipulate and extract values from.
For example, assuming the response is the one from your question:
$.ajax(settings).done(function (response) {
var parsedResponse = JSON.parse(response);
var token = parsedResponse.token;
console.log(token); // "wegHOIoi32h4gt834ygli"
});
Alternatively, if your API is correctly sending it's response with Content-Type: application/json
, or you tell jQuery to parse it as JSON for you (see dataType: "json"
in the documentation), then the problem is coming from the fact that $.each
tries to iterate over an array of value, which you don't have, so you can simply do this:
$.ajax(settingsIncudingDataType).done(function (response) {
var token = response.token;
console.log(token); // "wegHOIoi32h4gt834ygli"
});