从网站获取JSON并进入Javascript

Getting JSON from website and into Javascript

本文关键字:Javascript JSON 网站 获取      更新时间:2023-09-26

我正在尝试从Guardian api获取一些JSON数据,就像从这个例子http://content.guardianapis.com/search?q=Tim%20Farron%20mp&page-size=3&format=json一样 - 通过使用我编写的php程序。当我从数据中自行运行时,我的javascript发送给它,数据通常如上所示,但是当javascript运行时,它不会从php获得任何返回 - 代码被卡住。

PHP(工作(代码:

<?php
//gets url from passed over value
$url = urldecode($_GET['url']);
//gets  contents of url
$results = file_get_contents($url);
header('content-type: text/json');
echo $results;

这是我的 javascript 中不起作用的部分 - 没有返回响应,因为它卡在第一行。

$.getJSON('getSTORY.php?url='+ url2, function(response) {
 console.log(response);
 });

在控制台中,这是返回的错误消息(我认为!

XHR finished loading: "http://yrs2013.bugs3.com/mpapp/getSTORY.php?url=http%3A%2F%2Fcontent.guardianapis.com%2Fsearch%3Fq%3DTim%20Farron%20mp%26page-size%3D3%26format%3Djson". jquery.js:6
//^above was the link using the php. when pressed this shows the required JSON code
send jquery.js:6
x.extend.ajax jquery.js:6
x.(anonymous function) jquery.js:6
x.extend.getJSON jquery.js:6
(anonymous function) script.js:57
c jquery.js:4
p.fireWith jquery.js:4
k jquery.js:6
r

我想知道为什么程序卡住以及如何解决它,以及如何将变量从 php 传回 javascript!我对这一切很陌生,所以提前感谢!:)

您的代码应该可以正常工作,但请使用此作为参考:

$(function() { $('#test').bind('click', function(ev) { var url2="http://content.guardianapis.com/search?q=Tim%20Farron%20mp&page-size=3&format=json"; $.getJSON('test.php?url='+ url2, function(response) { console.log(response); $("#results").text(""+JSON.stringify(response)); if(response.response.status == "ok"){ $("#results").text(""); $.each(response.response.results, function(index, element) { $("#results").append($('<div>', { text: "Section: " + element.sectionName })); $("#results").append($('<div>', { text: "Title: " + element.webTitle })); $("#results").append($('<hr>')); }); $("#results").show(); } }); }); }); <form> <input type="button" name="test" id="test" value="test"> </form> <div id="results"> </div>

因此,您的问题很可能是您的 json 响应无效,因为上述代码中不存在 $url 的输出。所以请为将来:不要删除太多代码以将其发布在问题中,如果它只是用于调试目的的代码。

删除echo $results;前后的每个输出

您还应该更改的是 json 的内容类型,它application/json

header('content-type: application/json');

然后,要检查响应是否可以由 JSON 解析器处理,您可以使用 jsonlint 来验证 json。