??yy 2016-03-04 14:06 采纳率: 0%
浏览 8

访问多个JSON

In the console of the browser I have this: enter image description here

This is returned by this AJAX:

function displayFiles(){
var classElements = document.querySelectorAll("table.folders-list tr.ui-selected td span");
var csrf = $('input[name=_token]').val();
for(var x = 0;x < classElements.length;x++){
    var result;
    result = classElements[x].innerHTML;
    $.ajax({
        async: false,                      
        method: 'POST',
        dataType: 'json',
        url: '../public/getfiles',
        data: { 'folder': result, "_token": csrf  },
        success: function(data) {
        }
    });
}; 
}

I want to access them. Tried console.log(data[0].filename); but got an error. When there is a single JSON I get TypeError: data[0] is undefined, while if there are more than one (just like in the pic) nothing is returned. And this is the PHP function that sends that objects:

public function getFiles() {
    $folder = $_POST['folder'];
    $userid = Auth::id();
    $query = File::orderBy('created_at', 'desc')->where('userid', $userid)->where('folder', $folder)->get();
    // foreach for many result returned by $query
    foreach($query as $result){
        $arr = array();
        $arr['filename'] = $result->filename;
        $arr['id'] = $result->fileid;
        $arr['size'] = $result->conv_filesize;
        echo json_encode($arr);
    }      
}
  • 写回答

1条回答 默认 最新

  • 衫裤跑路 2016-03-04 14:25
    关注

    It seems like you are putting multiple JSON strings just next to each other. This in turn is no valid JSON.

    Your output looks something like {"x": 1}{"y": 2}, where it needs to be [{"x": 1},{"y": 2}].

    Try outputting all your data in a single call to json_encode():

    public function getFiles() {
        $folder = $_POST['folder'];
        $userid = Auth::id();
        $query = File::orderBy('created_at', 'desc')->where('userid', $userid)->where('folder', $folder)->get();
        // foreach for many result returned by $query
        $json = array();
        foreach($query as $result){
            $arr = array();
            $arr['filename'] = $result->filename;
            $arr['id'] = $result->fileid;
            $arr['size'] = $result->conv_filesize;
            $json[] = $arr;
        }    
        echo json_encode($json);
    }
    

    You might also try a JSON validator. ;)

    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因