jqueryコードをプレーンなjavascriptに置き換えようとしています。ディレクトリから画像を収集してjsonを出力するphpがあります。コードが表示されるパスを投稿する必要があります応答を得る前に画像のために。 これは私が何をそのエラーを知らない私は、これはPHPコードjson formated phpをバニラのjavascriptで取得する
<?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);
}
あるPHPファイルを読み込む
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xhr.onreadystatechange
というエラーが出る私は
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);
}
を持っているjsのです手段。
は、ここでは、HTML文字列(<
で始まる)の代わりに、JSON文字列を受けています
$.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');
}
});
jsonも投稿できますか? –
コンソールの[ネットワーク]タブでAJAXの応答を見て、スクリプトがJSONより前にHTMLを返す理由を確認してください。 – Barmar
あなたのPHPにはエラーがあり、 '<'はエラーメッセージの一部です。 @Barmarが提案したように、その答えを見つけてください。 –