2016-12-14 118 views
1

我刚开始与反应本地的,和我做的文档为基础的经典例子...获取JSON从JSONP获取承诺

fetch('https://facebook.github.io/react-native/movies.json') 
    .then((response) => response.json()) 
    .then((responseJson) => { 
    return responseJson.movies; 
    }) 
    .catch((error) => { 
    console.error(error); 
    }); 

这一切工作正常,在适当的JSON这个例子。

但是,在我的情况下,唯一可用的api响应是JSONP而不是JSON。没有基本的JSON可用。所以,我收到一个错误有关“(”。

因此,而不是像JSON

{"id": "1", "movies" : [ { "id" : "123" } ] } 

的我收到JSONP像

?({"id": "1", "movies" : [ { "id" : "123" } ] }); 

不过,我不确定我能做些什么来获得JSON如何通过获取promise来操作响应?我如何使用自己的函数来操作响应,还是有更自然的方式?

所以在第一个then()我不确定我能做什么得到o JSON(我尝试过对响应进行操作,但似乎只是看着承诺,所以我不确定react-native获取是如何操作的)。

+0

感谢downvote,将是有益的说为什么,这样我就可以改善。 – Ian

回答

3

我会建议使用response.text()而不是response.json(),删除周围的噪音,然后解析JSON字符串。

fetch('YOUR URL HERE') 
 
     .then((response) => response.text()) 
 
     .then((responseText) => { 
 
      const match = responseText.match(/\?\((.*)\);/); 
 
      if (! match) throw new Error('invalid JSONP response'); 
 
      return JSON.parse(match[1]).movies; 
 
     }) 
 
     .catch((error) => { 
 
      console.error(error); 
 
     });

+0

谢谢,非常有用。 – Ian