从网站获取JSON并进入Javascript
Getting JSON from website and into Javascript
我正在尝试从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。
相关文章:
- Javascript JSON.parse not working
- Javascript:JSON请求仅在第一次工作
- 定义this.properties或objectName.properties的javascript JSON对象
- Javascript/JSON警报返回Undefined
- 使用XPath样式访问Javascript JSON对象属性
- JavaScript JSON关联对象键和值都作为日期时间戳
- Javascript-JSON-嵌套和分组
- Javascript json返回未定义
- 无标题Javascript JSON数组->CSV导出
- Javascript JSON对象替换对象中的字符串
- Javascript/Json日期转换问题
- 使用jstl c:forEach在迭代jsp bean上创建javascript json对象
- 为什么我的JavaScript / JSON脚本不能在Internet Explorer中工作
- 将数据从 Python 发送到 Javascript (JSON)
- JavaScript Json 值追加基于相等条件
- 在设置用户后,从 JavaScript JSON 请求中获取 Web 服务 (asmx) ASP.NET Windows
- JavaScript - JSON 数据结构的构建 - 如何使用变量值更改键名
- Javascript JSON 解析和字符串化用于多级
- 如何将数据 php 更改为 javascript json
- Javascript JSON 到 Excel 文件下载