AJAX,JSON和PHP - 未捕获的SyntaxError:意外的令牌<

Ric*_*oss 0 php ajax json file-upload

所以我正在使用AJAX上传一个图像,我正在构建这个图像管理器工具...突然间它无法工作......我没有更改任何代码或任何东西.

.php运行并上传图像,但是在json被编码并发送回来之后我想要触发的事件没有发生.:/

控制台记录 Uncaught SyntaxError: Unexpected token <

另一个AJAX请求也发生了同样的事情,但第三个问题就好了......

在过去,当我收到此错误时,这是​​一个PHP语法错误,但我还没有更新.php一段时间.. soooo我难倒.

这是我的Javascript:

$("#chosenfile").change(function(){

    if($(this).attr('name')) {

        var data;

        data = new FormData();
        data.append('uploadedfile', $( '#chosenfile' )[0].files[0]);
        $('#loader').css('display','block');
        $.ajax({
            url: '/includes/uploadimage.php',
            data: data,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function ( data ) {
                //console.log(data); //returns a string of the data.
                var image = JSON.parse(data); //parses the string into an object.
                console.log(image); //logs the object.
                if (image.error) {
                    alert(image.error);
                    $('#remove').click();
                    $('#loader').css('display','none');
                } else {
                    if (image.link) { //If the image is uploaded and returned a link.
                        $('#remove').click();
                        $('#loader').css('display','none');
                        $('#scrollwindow').append("<div class='you'><img imgid='" + image.id + "' src='" + image.link + "' alt=''><span class='delete'>x</span></div>").fadeIn(200);
                        addToSlider(1);
                    };
                }
            }
        }); 

    }

});
Run Code Online (Sandbox Code Playgroud)

这是我的PHP:

<?php

include '../includes/global.php'; // General Vars and Functions I use sitewide.

/* ------------------------- */
/* -- Lets Get that file! -- */
/* ------------------------- */

    $file = $_FILES["uploadedfile"];

    $Return = array();
    $status = "failure";

/* ------------------------- */
/* - Okay, lets upload it! - */
/* ------------------------- */


    $Return["type"] = $file["type"];

    $target_path = "../uploads/"; // Define a folder to upload to

    $allowedExts = array("jpeg", "jpg", "JPG", "JPEG", "image/jpg"); // Array of allowed extensions.
    $extension = end(explode("/", $file["type"])); // Find extension.
    $maxsize = 2097152; // Get Max file size from hidden field in form.

    if ($file) {
        if (in_array($extension, $allowedExts)) // If the extension is allowed.
        {

            if(($file["size"] < $maxsize)) { // If size is less then max file size.

                $uploadResponse = "The file is a good size - ";

                $target_path = $target_path . basename($file['name']);  //Add file name string to upload folder destination string.
                $imageLink = "http://scoutsamerica.com/uploads/" . basename( $file['name']); // This is the full link

                if (file_exists($target_path)) { // If that file already exists, add a random integer to the end of it after a "_".

                    $uploadResponse .=  "This file exists: " . $target_path;

                    $randomNum = rand(1, 9999999);
                    $crudparts = explode(".", $file["name"]); //split filename and extension again.
                    $exceptExt =  $crudparts[0]; //Filename
                    $extension =  $crudparts[1]; //Extension
                    $target_path = "../uploads/" . $exceptExt . "_" . $randomNum . "." . $extension; //rename it with the random number.
                    $imageLink = "http://scoutsamerica.com/uploads/"  . $exceptExt . "_" . $randomNum . "." . $extension;

                    $uploadResponse .= " Path changed to: " . $target_path;
                }

                if(move_uploaded_file($file['tmp_name'], $target_path)) {
                        $uploadResponse .= "The file ".  basename( $file['name']) . " has been uploaded to " . $target_path . "</br></br>";

                    } else {
                        $uploadResponse .= "There was an error uploading the file, please try again! </br>";
                        $uploadResponse .= "File size: " . ($file["size"] / 1024) . "kb</br>";
                        $uploadResponse .= "Max size: " . ($maxsize / 1024) . "kb";
                    }

                $status = "success";
                $Return["link"] = $imageLink;

                /* ---------------------------------- */
                /* - Time to upload that image, yo. - */
                /* ---------------------------------- */

                $imageSql = "INSERT INTO images (id, link, model_id, addedon) VALUES (".
                    "null, " .
                    PrepSQL($imageLink) . ", " .
                    PrepSQL($myId) . ", " .
                    PrepSQL($date) . ")";

                mysql_query($imageSql) or die("Images: " . mysql_error());


            } else {
                $uploadResponse = "The file must less then " . ($maxsize / 1024) . "kb.";
                $status = "failure";
                $Return["error"] = $uploadResponse;
            }

        } else {
                $uploadResponse = "The file must be a .jpg file.";
                $status = "failure";
                $Return["error"] = $uploadResponse;
        }
    } else {
            $uploadResponse = "No Image.";
            $status = "failure";
            $Return["error"] = $uploadResponse;
    }


/* ------------------------- */
/* -  Lets Send it back :) - */
/* ------------------------- */

    $Return["status"] = $status;
    $Return["id"] = mysql_insert_id();
    $Return["traveler"] = $file;

    str_replace('\\/', '/', json_encode($Return));
    echo json_encode($Return);
?>
Run Code Online (Sandbox Code Playgroud)

原始响应:

<script>
    function hairEyesFind(haireyes){
        if (haireyes == "blonde") {
            return "z";
        };
        if (haireyes == "dirty blonde") {
            return "b";
        };
        if (haireyes == "auburn") {
            return "c";
        };
        if (haireyes == "brown") {
            return "d";
        };
        if (haireyes == "black") {
            return "e";
        };
        if (haireyes == "red") {
            return "f";
        };
        if (haireyes == "blue2") {
            return "g";
        };
        if (haireyes == "green2") {
            return "h";
        };
        if (haireyes == "hazel2") {
            return "i";
        };
        if (haireyes == "brown2") {
            return "j";
        };
    }
</script>{"type":"image\/jpeg","link":"http:\/\/scoutsamerica.com\/uploads\/485604_10201093620571706_1239548317_n_5119195.jpg","status":"success","id":281,"traveler":{"name":"485604_10201093620571706_1239548317_n.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpX1qywo","error":0,"size":60368}}
Run Code Online (Sandbox Code Playgroud)

Mar*_*c B 6

unexpected token可能意味着您从服务器获得了损坏的JSON响应.最有可能的是,它是一个html格式的PHP错误/警告,嵌入在json数据之前/之后,例如

<p>PHP Warning: blah blahblah</p>[...json text here ...]
Run Code Online (Sandbox Code Playgroud)

由于html无效json,您会收到该错误消息.因此,请检查服务器对该特定ajax调用的RAW响应,并查看从服务器返回的内容.