【问题标题】:Laravel 5 jquery getJSON not workingLaravel 5 jquery getJSON 不工作
【发布时间】:2017-06-08 15:31:27
【问题描述】:

我正在尝试从 Laravel 5 上的 API 获取 JSON 数据,路线给了我正确的 浏览器中的数据,但尝试在 JQuery 中访问此路由时失败。 路线是: http://localhost:8000/search/student/all

终于在浏览器中工作了,数据以json格式显示 但是这个脚本失败了:

 $(document).ready(function(){
     $("button").click(function(){
        $.getJSON("http://localhost:8000/search/student/all", function(result){
            $.each(result, function(i, field){
                $("div").append(field + " ");
            });
        });
    });
});

我将 localhost:8000 替换为 127.0.0.1:8000 但没有任何改变。

注意:我使用 Laravel 生成了 json 响应

$students=App\Student::all();
return response()->json($students);

【问题讨论】:

    标签: php jquery json laravel-5 csrf


    【解决方案1】:

    在 jquery 中你可以像下面这样做

    $.get( "http://localhost:8000/search/student/all", function(data ) {
      var obj = jQuery.parseJSON(data);
      console.log(obj);
    });
    

    另一种可能使用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(){
    
         }      
    });
    

    Basic example of using .ajax() with JSONP?

    【讨论】:

    • 谢谢,但问题在浏览器上仍然可以正常工作,但在 jquery 中没有检索到结果。
    • 好的日志给我这个错误:跨域请求被阻止:同源策略不允许读取localhost:8000/search/student/all(Reason的远程资源:CORS 标头“Access-Control-Allow-Origin”缺失)。
    • 如果对您有帮助,您可以接受它作为正确答案。这就是堆栈溢出的工作原理:)
    • @sumit toJson 在传递要打印为 JSON 响应的集合时不是必需的。 OP 的 PHP 代码很好。
    • 是的,他的问题与“CORS header”有关。我已经编辑了我的帖子
    【解决方案2】:

    试试这样...

    <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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多