How does one extract a value from a JSON returned by a web service in jQuery?

问题: 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"
});
  • 发表于 2019-01-14 17:27
  • 阅读 ( 245 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除