2016-08-27 28 views
0

使用JSON API获取数据时遇到的问题:如何使用JSON API从获取的json数据中删除整个脚本标记内容?

我使用的请求方法是:“ http://www.example.org/?json=get_post&post_id=47

但是返回的JSON文件带有一个<script>块,这引起了一个问题:

  <script> 
     document.cookie="kentopvc_22238=yes"; 
     </script> 

        <script> 
     document.cookie="kentopvc_22238=yes"; 
     </script> 

     {"status":"ok","post":{"id":22238,"type": ........... } 

error information

+1

的错误是与响应该请求的服务器应用程序。它是你的吗? – trincot

+0

服务器正在向您返回格式错误的JSON内容。具有“{..}”的内容的最后一部分看起来像它应该返回的实际内容,但不包含那些HTML标签的最高位。你拥有服务器吗?如果你不这样做,那么你可能需要通过从字符串 –

+0

中捕获'{...}'JSON来解决它。我会联系谁拥有该站点,并要求他们修复他们的API – NullUserException

回答

1

如果您无法访问返回格式错误的数据的API,则需要捕获字符串wit h正则表达式,然后解析它。然后

var jsonString = response.match(/^{.*$/m)[0] 
var parsedJson = JSON.parse(jsonString) 

正则表达式的解释

/ // beginning of pattern 
^ // starts at the beginning of a new line 
{ // looks for a bracket immediately following a new line 
.* // any subsequent characters 
$ // until we reach the end of the line 
/ // end of pattern 
m // the 'multiline' flag, necessary for the use of^

[0] // match() returns matches in an array. we want the first (and in this case only) match 
+0

嗨,我知道为什么api返回格式错误的数据,它是一个wordpress网站,我确实使用kentopvc插件来计算每篇文章的视图。我相信脚本块与kentopvc插件有关,也许我应该关闭它。但是,如果我真的计数我的网站的观点,我可以删除脚本块而不关闭插件?我可以使用一些JavaScript过滤器方法在角度js结束时删除