如何让jQuery .get返回JSON数据
How can I get jQuery .get to return JSON data?
我试图从URL中使用AJAX获取信息。这个URL将返回一个JSON响应,但我有很大的麻烦得到这个工作。我是相当新的使用AJAX和JSON,所以我不太确定我做错了什么。我没有收到任何输出。以下是目前为止的内容:
HTML:<!doctype html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content - Type">
<meta content ="utf-8" http-equiv="encoding">
<title>My Javascript Practice</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<noscript>JavaScript Must Be Enabled</noscript>
</head>
<body>
<div id="pub">Parent Div</div>
<script type="text/javascript" src="getList.js"></script>
</body>
</html>
JavaScript: var teamId = 883455;
var myUrl = "https://apps-internal.attributor.com/guardianapi/service/csadminservice/csteams/" + teamId + "?view=PUBLISHERS_FOR_TEAM";
$.get(myUrl, function(data){
$("#pub").html(data);
alert("load was performed");
});
我可以建议这样使用吗?
$.ajax({
type: 'GET',
url: myURL,
data: yourDAta,
dataType: 'jsonp',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('Error loading ');
}
});
注意jsonp
比json
的用法
只需添加json作为第三个参数,传递给回调的数据将是接收到的json字符串的对象表示
这个应该可以,
var teamId = 883455;
var myUrl = "https://apps-internal.attributor.com/guardianapi/service/csadminservice/csteams/" + teamId + "?view=PUBLISHERS_FOR_TEAM";
$.get(myUrl, function(data){
//data here will be object, should not used directly
$("#pub").html(data);
alert("load was performed");
}, 'json');
如果你在其他域,你可以设置服务器端脚本获取数据,比如PHP文件api。PHP
<?php
$teamId = $_GET['teamId'];
//php.ini should allow url fopen
$response = file_get_contents("https://apps-internal.attributor.com/guardianapi/service/csadminservice/csteams/". $teamId ."?view=PUBLISHERS_FOR_TEAM");
echo $response;
?>
并在js文件
中调用它var teamId = 883455;
var myUrl = "path/to/api.php?teamId="+teamId;
$.get(myUrl, function(data){
//data here will be object, should not used directly
console.log(data);
}, 'json');
如果您只对返回JSON响应感兴趣,请尝试使用getJSON()方法。
。get。load。getjson都是下面使用。ajax方法的扩展,如果无法使用扩展方法有时直接使用。ajax()会有帮助
getJSON()方法就是这样:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
注意数据类型的显式使用:"json"。
由于这看起来像一个跨域调用,如果您的端点支持的话,您将需要使用jsonp(带填充的JSON)或CORS(跨域资源共享)之类的东西。如果你的终端支持jsonp,你可以设置dataType: "jsonp",但它需要被服务器显式支持,详见这篇文章。
注意:您的服务器API 必须支持jsonp或CORS。
相关文章:
- Jquery:对返回JSON数据的php脚本的Ajax调用
- 返回JSON中的下标
- jQuery Map 从多个源返回 JSON 对象
- 如何在 Node.js 中返回 JSON 后停止代码流
- AngularJS:表单提交没有返回JSON中的值
- 使用ajax发送数据,返回json
- 从我的解析函数返回json
- 如何从脚本页面返回json数据
- 有些人有任何关于如何使用Modified Java Script Value处理返回Json(url)的示例
- 如何在html页面中从ajax返回json数据
- Ajax调用在本地返回json,但在服务器上运行时返回xml
- ajax调用返回JSON ParseError即使认为JSON看起来是正确的
- 调用.ajax方法得到未定义的json结果,返回json格式列表<字符串>
- 如何通过C#返回JSON并用JavaScript进行解析
- 使用 AJAX 返回 json 数组
- 从 AJAX 命令返回 JSON 格式的响应
- 如何通过node中的请求返回JSON.js(从javascript)
- Node.js API 在终端中返回 JSON,但不在浏览器中返回 JSON
- 如何在支柱 2 中返回 JSON 数组
- Rhino:从 Java 中返回 JSON