简体   繁体   English

Uncaught SyntaxError: Unexpected token < in JSON at position 0 with TinyMCE Editor Image Upload

[英]Uncaught SyntaxError: Unexpected token < in JSON at position 0 with TinyMCE Editor Image Upload

So I am working on a blog CMS and I am trying give my TinyMCE WYSIWYG editor the ability to upload images when a user is creating a post.所以我正在开发一个博客 CMS,我正在尝试让我的 TinyMCE WYSIWYG 编辑器能够在用户创建帖子时上传图像。 I'm using the actual code from the TinyMCE Docs ( https://www.tiny.cloud/docs/general-configuration-guide/upload-images/ ), but when I attempt to upload an image, it gets stuck loading and gives an error "Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.xhr.onload".我正在使用 TinyMCE Docs ( https://www.tiny.cloud/docs/general-configuration-guide/upload-images/ ) 中的实际代码,但是当我尝试上传图像时,它在加载和给出错误“Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.xhr.onload”。 Any ideas on what may be causing this?关于可能导致这种情况的任何想法? I've seen a few questions about this online, but they all seem to involve jQuery which I am not using.我在网上看到了一些关于这个的问题,但它们似乎都涉及我没有使用的 jQuery。 And sorry if this is too much of a question.对不起,如果这是一个太多的问题。 Thanks for your time.谢谢你的时间。

JavaScript (Top of body) JavaScript(身体顶部)

<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 (upload.php) PHP(上传.php)

<?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");
  }
?>

Thanks for the replies... It turns out I just needed the JS, PHP, and the upload folder to all be in the same folder.感谢您的回复...原来我只需要 JS、PHP 和上传文件夹都在同一个文件夹中。 Once I did that, it worked no problem.一旦我这样做了,它就没有问题了。 The code was good.代码很好。

Your json is returning html which is start with < tag instead of json response there.您的 json 正在返回以 < 标签开头的 html,而不是那里的 json 响应。 May be server error occurred.可能是服务器发生错误。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM