我无法使用此脚本在我的浏览器中显示来自 url 的 JSON 数据,但我找不到错误的来源。
url (http://www.entertainmentcocktail.com/cp/index.php) 包含我理解的有效 JSON 数据,但是当我使用此代码时没有返回任何内容:
<script type="text/javascript" src="cordova-2.3.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'http://www.entertainmentcocktail.com/cp/index.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var name = '<h1>'+item.location+'</h1>'
+ '<p>'+item.id+'</br>';
output.append(name);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
</script>
编辑:带有 JSON 数据的目标页面使用以下代码从数据库生成信息:
<?php
header('Content-type: application/json');
$server = "SERVER";
$username = "USER";
$password = "PASS";
$database = "DB";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT id, name, location FROM table_name ORDER BY id";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . json_encode($records);
?>