Javascript 如何解析远程服务器返回的 JSONP 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3543513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:05:59  来源:igfitidea点击:

How to parse JSONP data returned from remote server

javascriptjqueryajaxjsonjsonp

提问by patricksweeney

I am trying to grab some data via JSONP. Using Firebug, I am able to see the data properly being returned, but I am having a hard time thinking how I have to parse it. The data return is really a nested array correct? someFunctionis the name of the callback function. This is how the data looks:

我正在尝试通过 JSONP 获取一些数据。使用 Firebug,我能够看到正确返回的数据,但我很难思考如何解析它。数据返回真的是嵌套数组正确吗?someFunction是回调函数的名称。这是数据的样子:

someFunction([  
{  
       "title":"Sample Title",  
       "link":"http://example.com",  
       "description":"Sample Description",  
       "publisher":"Sample Publisher",  
       "creator":"Sample Author",  
       "date":"Thu, 19 Aug 2010 12:41:29 GMT",  
       "num_pages":10,  
       "num_results":"10"  
},  
]);

Just a little confused about how to properly parse and output.

只是对如何正确解析和输出有点困惑。

回答by Anurag

You don't have to parse the data. It is already a valid JavaScript object. For instance, to print the description property for the first object inside someFunction

您不必解析数据。它已经是一个有效的 JavaScript 对象。例如,打印 someFunction 中第一个对象的描述属性

function someFunction(result) {
    alert(result[0].description); // alerts "Sample Description"
}

回答by Quentin

Write a function with the correct name and the correct arguments. The JS engine will do the parsing for you.

用正确的名称和正确的参数编写一个函数。JS 引擎会为你做解析。

function someFunction(data) {
    // Now data is an Array, containing a single
    // Object with 8 properties (title, link, etc)
}