Laravel 5 jquery getJSON不工作
问题描述:
我想从Laravel 5上的API获取JSON数据,该路线给了我正确的 浏览器中的数据,但是当尝试在JQuery中访问此路由时失败。 的路线是: http://localhost:8000/search/student/allLaravel 5 jquery getJSON不工作
终于先后在浏览器中的数据显示JSON格式 但这个脚本失败:
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://localhost:8000/search/student/all", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
我换成本地主机:8000 127.0.0.1:8000但没有改变。
注:我生成使用Laravel
$students=App\Student::all();
return response()->json($students);
答
jQuery的JSON响应,你可以做喜欢的事,下面
$.get("http://localhost:8000/search/student/all", function(data) {
var obj = jQuery.parseJSON(data);
console.log(obj);
});
Another possibility use jsonp
JSONP确实是一个简单的技巧来克服XMLHttpRequest的同域策略。 (正如你知道一个无法发送AJAX(XMLHttpRequest的)请求到不同的域。)
$.ajax({
url:"http://localhost:8000/search/student/all",
dataType: 'jsonp',
success:function(data){
var obj = jQuery.parseJSON(data);
console.log(obj)
},
error:function(){
}
});
答
尝试像这样...
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://localhost:8000/search/student/all", function(result){
$.each(result.students, function(i, field){
$("div").append(field.name + " ");//name is database field name such as id,name,address etc
});
});
});
</script>
PHP
$students=App\Student::all();
echo json_encode($students);//or return $students->toJson();
谢谢,但问题仍然是在浏览器上工作正常,但在jQuery中没有检索到任何结果。 – mahmoud
编辑我的答案 – sumit
确定日志给我这个错误: 跨源请求被阻止:同源策略不允许读取http:// localhost:8000/search/student/all中的远程资源(原因:CORS头'访问-Control-Allow-Origin'缺失)。 – mahmoud