Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未捕获的语法错误:意外标记<;在位置0的JSON中,使用TinyMCE编辑器上载图像_Javascript_Php_Tinymce - Fatal编程技术网

Javascript 未捕获的语法错误:意外标记<;在位置0的JSON中,使用TinyMCE编辑器上载图像

Javascript 未捕获的语法错误:意外标记<;在位置0的JSON中,使用TinyMCE编辑器上载图像,javascript,php,tinymce,Javascript,Php,Tinymce,因此,我正在开发一个博客CMS,我正在尝试让我的TinyMCE WYSIWYG编辑器能够在用户创建帖子时上传图像。我使用的是TinyMCE Docs()中的实际代码,但当我尝试上载图像时,它在加载时遇到了问题,并给出了一个错误“Uncaught SyntaxError:Unexpected token

因此,我正在开发一个博客CMS,我正在尝试让我的TinyMCE WYSIWYG编辑器能够在用户创建帖子时上传图像。我使用的是TinyMCE Docs()中的实际代码,但当我尝试上载图像时,它在加载时遇到了问题,并给出了一个错误“Uncaught SyntaxError:Unexpected token<在JSON中位于XMLHttpRequest.xhr.onload的JSON.parse()位置0处”。你知道是什么导致了这一切吗?我在网上看到了一些关于这个的问题,但它们似乎都涉及到我没有使用的jQuery。如果这是个太多的问题,我很抱歉。谢谢你抽出时间

JavaScript(正文顶部)


函数示例\u图像\u上载\u处理程序(blobInfo、成功、失败、进度){
var-xhr,formData;
xhr=newXMLHttpRequest();
xhr.withCredentials=false;
open('POST','upload.php');
xhr.upload.onprogress=函数(e){
进度(e.loaded/e.total*100);
};
xhr.onload=函数(){
var-json;
如果(xhr.status==403){
失败('HTTP错误:'+xhr.status,{remove:true});
返回;
}
如果(xhr.status<200 | | xhr.status>=300){
失败('HTTP错误:'+xhr.status);
返回;
}
json=json.parse(xhr.responseText);
如果(!json | | typeof json.location!=“string”){
失败(“无效的JSON:”+xhr.responseText);
返回;
}
成功(json.location);
};
xhr.onerror=函数(){
失败('由于XHR传输错误,图像上载失败。代码:'+XHR.status);
};
formData=新的formData();
append('file',blobInfo.blob(),blobInfo.filename());
xhr.send(formData);
};
tinymce.init({
选择器:“#tinymce”,
身高:450,
插件:[
“advlist autolink图像列表charmap打印预览hr锚定pagebreak”,
“searchreplace wordcount visualblocks visualchars代码全屏插入日期时间媒体非中断”,
“表格表情模板粘贴帮助”
],
工具栏:“撤消重做|样式选择|粗体斜体|左对齐居中对齐右对齐对齐对齐|”+
“bullist numlist outdent缩进|链接图像|打印预览媒体全页|”+
“前景色背景表情|帮助”,
菜单:{
favs:{title:'My Favorites',items:'code visualaid | searchreplace | emoticons'}
},
菜单栏:“favs文件编辑视图插入格式工具表帮助”,
content_css:'css/content.css',
图片上传处理程序:示例图片上传处理程序
});
PHP(upload.PHP)


感谢您的回复。。。事实证明,我只需要将JS、PHP和upload文件夹放在同一个文件夹中。一旦我这么做了,就没问题了。代码很好。

您的json返回的html以

按f12键,转到“网络”选项卡,查看从服务器加载的内容。。。意外标记<当您期望json时,是php发送错误消息而不是json时作为响应发送的第一个标记。。。用f12检查开发工具中的响应,你应该能够看到哪里出了问题。所以我在网络选项卡中查看了一下,我得到的唯一404是TinyMCE CDN中的“content.css”。控制台选项卡显示错误位于
json=json.parse(xhr.responseText)根据我所知,这是返回的响应:“{”location:“post img\/sunset.jpg”}”。TinyMCE文档说,响应应该是这样的:“{location:'/upload/image/path/image.png'}”。同样,在第48行的C:\xampp\htdocs\site\blog admin\upload.php中出现了这个错误“无法打开流:HTTP包装器不支持可写连接”。我确保了所有路径都是正确的,现在得到了这个响应:“{”位置“:“http:\/\/localhost\/blog kellumws\/post img\/consite.jpg”}”在我看来,它同时添加了反斜杠和正斜杠似乎很奇怪。这可能是问题所在吗?您得到的响应是基本json?。。。您不是在寻找404,而是在寻找正在发送的有问题的响应。响应预览是有效的json-不是php错误?
<script>
    function example_image_upload_handler (blobInfo, success, failure, progress) {
        var xhr, formData;

        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', 'upload.php');

        xhr.upload.onprogress = function (e) {
            progress(e.loaded / e.total * 100);
        };

        xhr.onload = function() {
            var json;

            if (xhr.status === 403) {
                failure('HTTP Error: ' + xhr.status, { remove: true });
                return;
            }

            if (xhr.status < 200 || xhr.status >= 300) {
                failure('HTTP Error: ' + xhr.status);
                return;
            }

            json = JSON.parse(xhr.responseText);

            if (!json || typeof json.location != 'string') {
                failure('Invalid JSON: ' + xhr.responseText);
                return;
            }

            success(json.location);
        };

        xhr.onerror = function () {
            failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
        };

        formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());

        xhr.send(formData);
    };

    tinymce.init({
        selector: '#tinymce',
        height: 450,
        plugins: [
        'advlist autolink link image lists charmap print preview hr anchor pagebreak',
        'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
        'table emoticons template paste help'
        ],
        toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' +
        'bullist numlist outdent indent | link image | print preview media fullpage | ' +
        'forecolor backcolor emoticons | help',
        menu: {
        favs: {title: 'My Favorites', items: 'code visualaid | searchreplace | emoticons'}
        },
        menubar: 'favs file edit view insert format tools table help',
        content_css: 'css/content.css',
        images_upload_handler: example_image_upload_handler
    });
</script>
<?php
  $accepted_origins = array("http://localhost");
  $imageFolder = "post-img/";

  reset ($_FILES);
  $temp = current($_FILES);
  if (is_uploaded_file($temp['tmp_name'])){
    if (isset($_SERVER['HTTP_ORIGIN'])) {
      // same-origin requests won't set an origin. If the origin is set, it must be valid.
      if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
      } else {
        header("HTTP/1.1 403 Origin Denied");
        return;
      }
    }

    /*
      If your script needs to receive cookies, set images_upload_credentials : true in
      the configuration and enable the following two headers.
    */
    // header('Access-Control-Allow-Credentials: true');
    // header('P3P: CP="There is no P3P policy."');

    // Sanitize input
    if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
        header("HTTP/1.1 400 Invalid file name.");
        return;
    }

    // Verify extension
    if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
        header("HTTP/1.1 400 Invalid extension.");
        return;
    }

    // Accept upload if there was no origin, or if it is an accepted origin
    $filetowrite = $imageFolder . $temp['name'];
    move_uploaded_file($temp['tmp_name'], $filetowrite);

    // Respond to the successful upload with JSON.
    // Use a location key to specify the path to the saved image resource.
    // { location : '/your/uploaded/image/file'}
    echo json_encode(array('location' => $filetowrite));
  } else {
    // Notify editor that the upload failed
    header("HTTP/1.1 500 Server Error");
  }
?>