使用vanilla javascript获取json格式化的php

时间:2017-09-07 16:25:59

标签: javascript php json

所以我试图用普通的javascript替换一些jquery代码,我有一个从目录中收集图像并输出json的php,我需要在获取之前发布代码查找图像的路径响应。 这是我的js

    let imgpath = '&img_path=img/' + directory    
    loadJSON(dataUrl, successJson, errorJson);
    function successJson(data)
    { 
        console.log(data);
    };
    function errorJson(xhr)
    { 
        console.log('Error :('); 
    };
    //
    function loadJSON(path, success, error)
    {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", path, true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onreadystatechange = function()
        {
            if(xhr.readyState === XMLHttpRequest.DONE)
            {
                if((xhr.status === 200 || xhr.status === 0) && success) success(JSON.parse(xhr.responseText));
                else{if(error) error(xhr);}
            }
        };
        xhr.send(imgpath);
    }

我收到读取php文件的错误

Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xhr.onreadystatechange

这是php代码

<?php
//
$dir = $_POST['img_path'];
//
if(is_dir($dir))
{
    if($dh = opendir($dir))
        while(($file = readdir($dh)) != false)
            if($file != "." and $file != ".." and $file != ".DS_Store" and $file != "zoom") $files_array[] = array('file' => $file);
    $return_array = array('images' => $files_array);
    //
    header('Content-type: application/json');
    echo json_encode($return_array);
}

我不知道这个错误意味着什么。

这是可以正常工作的Jquery代码

    $.ajax({
        type: 'POST',
        url: dataUrl,
        data: imgpath,
        beforeSend: function(xhr){if(xhr.overrideMimeType) xhr.overrideMimeType('application/json');},
        success: function(data)
        {
            console.log(data);
        },
        error: function()
        {
            console.log('error');
        }
    });

2 个答案:

答案 0 :(得分:0)

它正在接收一个html字符串(以$diff = ($truckHistory->created_at - $model->created_at); return $diff 开头)而不是JSON字符串。

PHP脚本中必定存在错误,导致它返回HTML而不是JSON。

答案 1 :(得分:0)

您正在发送一个URL编码的POST参数,因此您不应将Content-type请求标头设置为application/json。摆脱这一行:

    xhr.setRequestHeader('Content-Type', 'application/json');

PHP无法将JSON参数解析为$_POST。我猜测当它看不到它理解的Content-type时,它不会填充$_POST,因此您会收到Undefined index警告。