在PHP-MVC中使用AJAX

在PHP-MVC中使用AJAX,php,ajax,file-upload,tinymce,Php,Ajax,File Upload,Tinymce,我正在尝试使用tinyMCE和php中的MVC框架。但是我在使用AJAX和MVC框架时遇到了问题 我已经将upload处理程序设置为转到“upload.php”,并获得一个带有文件名和文件位置的JSON对象。但是,我的index.php页面以HTML格式返回,这给了我一个错误: VM1541:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>

我正在尝试使用tinyMCE和php中的MVC框架。但是我在使用AJAX和MVC框架时遇到了问题

我已经将upload处理程序设置为转到“upload.php”,并获得一个带有文件名和文件位置的JSON对象。但是,我的index.php页面以HTML格式返回,这给了我一个错误:

VM1541:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.xhr.onload (add:42)
这是我的上传处理程序:

tinymce.init({
selector: '#tinymcebody',
plugins: "image",
menubar: "insert",
toolbar: "image",
images_upload_url: './posts/upload.php',

images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;

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

xhr.onload = function() {
  var json;

  if (xhr.status != 200) {
    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);
};

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

xhr.send(formData);
}
这是我的upload.php:

<?php
// Allowed origins to upload images
$accepted_origins = array("http://localhost");

// Images upload path
$imageFolder = echo URLROOT . '/public/images';

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

还需要这方面的帮助吗?我可以提供帮助,因为您在PHP中使用的是
json\u encode
,所以您希望响应是json编码的字符串。尽管如此,在JS中,您没有使用
xhr.responseType='json'将设置为“json”。请注意,该设置的默认值为空字符串。另外,您会说:“相反,响应是整个文档”。阅读返回的内容!您很可能会在其中发现特定的错误文本。@dakis我将响应类型设置为json,但随后出现错误:Uncaught DomeException:未能从“XMLHttpRequest”读取“responseText”属性:仅当对象的“responseType”为“”或“text”(是“json”)时,才可访问该值。在XMLHttpRequest.xhr.onload。我在回复中没有看到任何具体的错误文本。它不应该是一个html文档,upload.php应该返回一个json对象,而不是根html文档。@FernandoUrban是的,我需要帮助,仍然无法解决。我想我发现了问题,我是对的,它与MVC中的路由有关。我会更新我的帖子,如果你能帮忙,请阅读@达基斯
<?php
// Allowed origins to upload images
$accepted_origins = array("http://localhost");

// Images upload path
$imageFolder = echo URLROOT . '/public/images';

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