JavaScript处理REST JSON提要 [英] JavaScript to Handle REST JSON Feed

查看:93
本文介绍了JavaScript处理REST JSON提要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图弄清楚用于处理REST服务返回的JSON feed的JavaScript语法.假设随机的REST服务(例如 http://random.service/directory )返回以下供稿:

Trying to figure out the JavaScript syntax for handling JSON feed returned by a REST service. Suppose a random REST service (e.g. http://random.service/directory) is returning the following feed:

{
  'firstName': 'John',
  'lastName': 'Smith',
  'address': {
      'streetAddress': '21 2nd Street',
      'city': 'New York'
  }
}

并且我有一个JSON解析JS函数(以解析上面的提要),如:

and that I have a JSON parsing JS function (to parse the above feed) like:

function parseRESTFeed(json) {
  ...
}

如何通过JS将"http://random.service/hello"的REST调用桥接到parseRESTFeed(json)?

How do I bridge the REST call of "http://random.service/hello" to parseRESTFeed(json) via JS?

非常感谢!

推荐答案

如果使用jQuery(如果不使用,则应该这样做),则可以这样做(

If you use jQuery (and you should if you don't), then you can do it like this (ref):

$.getJSON('http://random.service/directory', null, function(data){
    // And here you can do whatever you want with "data", no need to parse it
    alert(data.firstName);
});

如果您有其他方法可以从服务获取响应作为字符串,则也没有理由解析,因为您可以使用javascript的eval.例如:

If you have some other way to get response from the service as string, again there is no reason to parse, since you can use javascript's eval. For example:

var myJSON = "{'firstName': 'John','lastNAme': 'Smith'}";
var data = eval('(' + myJSON + ')');
alert(data.firstName);

这篇关于JavaScript处理REST JSON提要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆