嘿伙计我无法获取跨域json数据这里是我的代码,下面没有工作
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="js/jquery.min.js"></script>
</head>
<body>
<div id="images"></div>
<script>
(function() {
var furl= "http://192.168.2.36/gemadmin/display.php?callback=?";
$.getJSON( furl)
.done(function( data ) {
console.log(data);
});
})();
</script>
</body>
</html>
并且此代码正常工作,因为它只是localhost
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="js/jquery.min.js"></script>
</head>
<body>
<div id="images"></div>
<script>
(function() {
var furl= "http://localhost/gemadmin/display.php";
$.getJSON( furl)
.done(function( data ) {
console.log(data);
});
})();
</script>
</body>
</html>
为什么第一个版本不起作用?什么是使它工作的解决方案?
服务器代码(display.php)
<?php
include 'config.php';
$sql = "select * from menu;";
$result= $mysqli->query($sql);
$data = $result->fetch_all( MYSQLI_ASSOC );
header('Content-Type: application/json');
echo json_encode( $data );
?>
答案: 找到答案而不是$ .getJSON()使用$ .get并执行json解析 例 jQuery.getJSON演示 img { 身高:100px; 向左飘浮; }
<div id="images"></div>
<script>
(function() {
var furl= "http://localhost/gemadmin/display.php?callback=?";
$.get( furl)
.done(function( data ) {
var obj = JSON.parse(data);
console.log(obj);
});
})();
</script>
</body>
</html>
不要忘记在网址中添加&#39; 回调=?&#39;
答案 0 :(得分:0)
像这样使用
$.ajax({
url: "URL",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify("YOUR JSON"),
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});
答案 1 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
demo_ajax_json.js
{
"firstName": "John",
"lastName": "Doe",
"age": 25
}
一个简单的例子