我正在尝试使用 get 请求调用以下网址。
http://localhost:8080/abc/employees
当我在浏览器中打开上述网址时,我收到以下响应。
[{"firstName":"Hari Krishna","id":1,"lastName":"Gurram","permAddrees":{"area":"Marthali","city":"Bangalore","country":"India","state":"Karnataka"},"tempAddrees":{"area":"Electronic City","city":"Bangalore","country":"India","state":"Karnataka"}},{"firstName":"PTR","id":2,"lastName":"PTR","permAddrees":{"area":"Bharath Nagar","city":"Hyderabad","country":"India","state":"Andhra Pradesh"},"tempAddrees":{"area":"BTM Layout","city":"Bangalore","country":"India","state":"Karnataka"}}]
以下是我的 jquery 片段。
<!DOCTYPE html>
<html>
<head>
<script src = "jquery-3.1.0.js"></script>
</head>
<body>
<h1>Click the below button to see the AJAX response</h1>
<input type="submit" value="click here" id="button1" />
<div id="placeHolder">
</div>
<script type="text/javascript">
var jq = jQuery.noConflict();
jq(document).ready(function(){
jq("#button1").click(function(){
alert("Hello");
jq.get("http://localhost:8080/abc/employees", function(data, status){
alert(data + "" + status);
jq("#placeHolder").html(response);
});
});
});
</script>
</body>
</html>
当我单击按钮时,它显示第一个警报框“alert("Hello");”,但回调函数中的警报框未执行。任何人都可以帮我解决我的代码的问题吗?
最佳答案
简短回答
Safari 允许,而 Chrome 不允许(跨源请求共享 - CORS)。
实验:
让我们执行来自此 html file 的请求从我们的“localhost”到“www.google.com”。
Chrome 中会发生什么?
在 chrome 中,不允许 CORS(跨域请求共享),因此它会阻止您这样做。
Safari 中会发生什么?
Safari 允许这种行为,因此您会收到以下响应 <强> http://www.google.com
关于jquery:ajax 获取请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39001878/