我有一个要求是通过Ajax获取跨域json数据。我需要维护2个不同的服务器(服务器A和服务器B)。跨域Ajax数据
服务器A只包含静态内容。 ie:JS,Images,Css
服务器B只包含动态内容 即。 php驱动脚本
根据上述要求,我在本地pc上设置并成功配置了Nginx + Apache环境。
我在本地主机上运行了两个域。
服务器A:http://localhost:9000/
>上Nginx的运行作为静态内容前端
服务器B:http://localhost:8888/
>在Apache上运行作为用于动态内容(即PHP)
服务器A包含一个后端
index.html jquery和 自定义Ajax处理java脚本。
的index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="./js/jquery-1.7.2.min.js" type="application/javascript"></script>
<script src="./js/script.js" type="application/javascript"></script>
<title>Ajax</title>
</head>
<body>
<div id="result"></div>
</body>
</html>
的script.js
$(document).ready(function(e) {
var url = 'http://localhost:8888/drp/application/ajax.php';
var success = function(data){
var set = "";
set += "Name: "+ data['fname']+ " " + data['lname']+"<br>";
set += "Age: "+ data['age']+"<br>";
set += "Address: "+ data['address']+"<br>";
set += "Email: "+ data['email']+"<br>";
set += "Web: "+ data['web']+"<br>";
$('#result').html(set);
};
var error = function(jqXHR, textStatus, errorThrown){
//alert(errorThrown);
alert('errorThrown');
};
$.ajax({
type: 'GET',
url: url,
data:{todo:"jsonp"},
dataType: "jsonp",
crossDomain: true,
cache:false,
success: success,
error: error
});
});
服务器2含有ajax.php其是处理Ajax请求
ajax.php
<?php
#header('Content-Type: application/json');
header('Content-Type: application/javascript');
$x = array(
'fname' => 'Jone',
'lname' => 'Max',
'age' => '26',
'address' => 'London,Uk',
'email' => '[email protected]',
'web' => 'http://jonemaxtest.com',
);
print json_encode($x,true);
?>
当我打电话时这个前端index.html,我可以看到这样的错误
SyntaxError: missing ; before statement
{"fname":"Jone"...}
我试过所以可能时间,但我没有得到正确的结果。每次我收到这种错误信息。我也试图改变标题('Content-Type:application/javascript');到头('Content-Type:application/json');但没有工作。
我在那个代码集中犯了我的错误...?
请帮帮我。
你好萨拉特 你的修改是完全正确的。它为我工作。非常感谢你。 – Umanda
不用客气。如果有帮助,请将答案标记为正确。 – SarathSprakash