使用 Javascript/JQuery 检索 JSON GET 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14480502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve JSON GET data with Javascript/JQuery
提问by Ben
What I am trying to do isretrieve JSON data from an online web service that searches and finds a certain string in a MySQL database and display it using Javascript on an HTML page.
我想要做的是从在线 Web 服务中检索 JSON 数据,该服务在 MySQL 数据库中搜索并找到某个字符串,并在 HTML 页面上使用 Javascript 显示它。
What I am struggling with isactually displaying the resulting data.
我正在努力解决的问题实际上是显示结果数据。
The relevant areas of my HTML page looks like this:
我的 HTML 页面的相关区域如下所示:
<form onSubmit="results()">
<fieldset>
<label for="area">First digits of postal code:</label>
<input name="area" type="text" maxlength="4" placeholder="AB12" required />
<input type="submit" value="Search" name="search" />
</fieldset>
</form>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="cordova-2.3.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
function results(){
$.ajax({
url: 'http://www.foobar.com/cp/index.php?area=AB12',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<h1>'+item.location+'</h1>'
+ '<p>'+item.id+'</br>';
output.append(place);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
};
</script>
<div id="place">
<h3>Places near your location</h3>
</div>
The page for the GET data is http://www.foobar.com/cp/index.phpwith the search variable 'area'. Test sample is ?area=AB12.
GET 数据的页面是http://www.foobar.com/cp/index.php,搜索变量为“area”。测试样本是 ?area=AB12。
采纳答案by rsp
It seems that this service is not correctly wrapping the JSON object in parentheses so it doesn't work as JSONP.
该服务似乎没有正确地将 JSON 对象包装在括号中,因此它不能作为 JSONP 工作。
See: http://www.entertainmentcocktail.com/cp/index.php?area=AB12&jsoncallback=TEST
参见:http: //www.entertainmentcocktail.com/cp/index.php?area=AB12&jsoncallback=TEST
It returns:
它返回:
TEST[{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]
while it shouldreturn:
虽然它应该返回:
TEST([{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]);
You won't be able to use it because it is not valid JSONP.
您将无法使用它,因为它不是有效的 JSONP。
UPDATE:
更新:
Answering more info from the comment - if you control the server-side script then try changing:
从评论中回答更多信息 - 如果您控制服务器端脚本,请尝试更改:
while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . json_encode($records);
to:
到:
while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
and see if that works.
看看这是否有效。
UPDATE 2:
更新 2:
Answering another comment. Do you actually initialize the output
variable? For example with something like this at the beginning:
回答另一个评论。你真的初始化了output
变量吗?例如,开头是这样的:
var output = $('#place').append('<div/>');
Do you actually call your results
function? It must be called with:
你真的调用你的results
函数吗?必须使用以下命令调用它:
results();
or registered somewhere as an event handler, using the jQuery way:
或在某处注册为事件处理程序,使用 jQuery 方式:
$('form').submit(results);
but then add:
然后添加:
return false;
to the end of the results
function to prevent the page from being reloaded.
到results
函数的末尾以防止页面被重新加载。
See this demo: http://jsbin.com/uziyek/1/edit- it seems to work.
看到这个演示:http: //jsbin.com/uziyek/1/edit- 它似乎工作。
Another problem:
另一个问题:
There seems to be another problem with your code, that the area=AB12 parameter is hardcoded into your URL. What you should do instead is get the value from the form and send that.
您的代码似乎还有另一个问题,即 area=AB12 参数被硬编码到您的 URL 中。你应该做的是从表单中获取值并发送它。
回答by Felix Kling
You implemented JSONP incorrectly. You need to generate a function call, i.e. the response should be foo(<json here>);
not foo<json here>
.
您错误地实施了 JSONP。你需要生成一个函数调用,即反应应该是foo(<json here>);
没有foo<json here>
。
It is trivial to fix:
修复很简单:
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
Another problem is that you are not preventing the form submission, i.e. when you submit the form, the page refreshes. You have to prevent that. Better bind the event handler with jQuery and don't use inline event handlers:
另一个问题是您没有阻止表单提交,即当您提交表单时,页面会刷新。你必须防止这种情况。最好用 jQuery 绑定事件处理程序,不要使用内联事件处理程序:
<form id="myForm">
and
和
$(function() {
$('#myForm').submit(function(event) {
event.preventDefault(); // <-- prevent form submission
// Ajax call here
});
});