尝试从AJAX调用返回数据时出现意外结果

时间:2018-07-30 22:11:01

标签: php jquery ajax

我有以下脚本,用于将图像,目录名称和可能的替代文件名发送到php文件中的操作网址。

    $(document).ready(function() {
    $(".layout-save").click(function(e) {
        e.preventDefault();     
        var form = $(".image_define");
        var params = form.serializeArray();
        var formData = new FormData();
        formData.append('default_image', $('#default_image')[0].files[0]);
        $(params).each(function (index, element) {
            formData.append(element.name, element.value);
        });
        $.ajax({
            url: form.attr('action'),
            method: "post",
            data: formData,
            contentType: false,
            processData: false
            })
        .done(function(data) {
            var obj = JSON.parse(data);
            $('.tooltip-imageHandler-<?php echo $products_filter; ?>').tooltipster('close');
            var elem = $('.image-<?php echo $products_filter; ?>');
            elem.fadeOut('slow', function() {
                elem.html(obj.asHtml).fadeIn('slow', function() {
                    elem.delay(1200).fadeOut('slow', function() {
                        elem.html(obj.products_image).fadeIn('slow');
                    });
                });
            });
        })
        .fail(function(){
            alert('Ajax Submit for New Image Save Failed ...'); 
        });
    });
});

我试图实现的目标是发回一条成功消息,该消息可以显示在image-xxx类中,其中xxx是产品ID,因此当页面上有多个实例时,可以给出唯一的类名。

文件上传正常,并且工具提示正确关闭。在更新数据库的最终sql查询之后,我在“保存”情况下添加了以下代码行:

echo json_encode(array("products_image"=>$data['defaultFileName'], "asHtml" => '<div class="alert alert-info update-notice update-'.$products_filter.'"><strong>Product image updated</strong></div>'));

我希望能够使用它来显示成功消息,然后使用新上传的图像更新div。

但是,在测试时,我在控制台中得到了以下内容 “ VM3150:2 Uncaught SyntaxError:JSON中位置162上的意外令牌<” 并且如果我console.log(data)我看到的是页面解析的php,而不仅仅是“ products_image”和“ asHtml”。

有人可以提供一些关于我在这里做错了什么的指点吗?

注意:虽然我知道我可以接受通过表单提交的数据,但是在处理完信息后,我确实需要这些信息,因为它取决于文件路径和图像命名等内容(取决于是否是第一个),或其他图像写入数据库之前。

从if($ action =='save')所在的文件中添加了php。 json_encode在末尾约12行,紧接在显示原始(pre ajax修改)成功消息之后。

if ($action == 'save') {
// -----
// Log the input values on entry, if debug is enabled.
//
$ih_admin->debugLog(
    'ih_manager/save, on entry.' . PHP_EOL . 
    '$_GET:' . PHP_EOL . var_export($_GET, true) . PHP_EOL . 
    '$_POST:' . PHP_EOL . var_export($_POST, true) . PHP_EOL . 
    '$_FILES:' . PHP_EOL . var_export($_FILES, true)
);

// -----
// Set some processing flags, based on the type of upload being performed.
//
$editing = (isset($_GET['imgEdit']) && $_GET['imgEdit'] == '1');
$new_image = (isset($_GET['newImg']) && $_GET['newImg'] == '1');
$main_image = (!isset($_GET['imgSuffix']) || $_GET['imgSuffix'] == '');
$keep_name = (isset($_POST['imgNaming']) && $_POST['imgNaming'] == 'keep_name');

$data = array();
$data_ok = true;

// -----
// Determine the extension required for any uploaded images.
//
// 1) A new main-image (and any medium/large) use the extension from the (required) default image suppied.
// 2) A new additional image's files use the extension from the pre-existing main-image.
// 3) Editing an image uses the pre-existing file extension.
//
if ($new_image) {
    if ($_FILES['default_image']['name'] == '') {
        $messageStack->add(TEXT_MSG_NO_DEFAULT, 'error');
        $data_ok = false;
    } else {
        $data['imgExtension'] = '.' . pathinfo($_FILES['default_image']['name'], PATHINFO_EXTENSION);
    }
} else {
    $data['imgExtension'] = $_GET['imgExtension'];
}

// -----
// If the file-upload is in support of a new main image or the main image is being edited ...
//
if ($new_image || ($editing && $main_image && !$keep_name && $_FILES['default_image']['name'] != '')) {
    // New Image Name and Base Dir
    if (isset($_POST['imgBase']) && $_POST['imgBase'] != '') {
        $data['imgBase'] = $_POST['imgBase'];
    } else {
        // Extract the name from the default file
        if ($_FILES['default_image']['name'] != '') {
            $data['imgBase'] = pathinfo($_FILES['default_image']['name'], PATHINFO_FILENAME);
        } else {
            $messageStack->add(TEXT_MSG_AUTO_BASE_ERROR, 'error');
            $data_ok = false;
        }
    }

    // catch nasty characters
    if (strpos($data['imgBase'], '+') !== false) {
        $data['imgBase'] = str_replace('+', '-', $data['imgBase']);
        $messageStack->add(TEXT_MSG_AUTO_REPLACE . $data['imgBase'], 'warning');
    }

    if (isset($_POST['imgNewBaseDir']) && $_POST['imgNewBaseDir'] != '') {
        $data['imgBaseDir'] = $_POST['imgNewBaseDir'];
    } elseif (isset($_POST['imgBaseDir'])) {
        $data['imgBaseDir'] = $_POST['imgBaseDir'];
    } else {
        $data['imgBaseDir'] = $_GET['imgBaseDir'];
    }

    $data['imgSuffix'] = '';

// -----
// Otherwise, if we're editing an additional product image ...
//
} elseif ($editing) {
    $data['imgBaseDir'] = $_GET['imgBaseDir'];
    $data['imgBase'] = $_GET['imgBase'];
    $data['imgSuffix'] = $_GET['imgSuffix'];
// -----
// Otherwise, we're adding an additional product image ...
//
} else {
    // An additional image is being added
    $data['imgBaseDir'] = $_GET['imgBaseDir'];
    $data['imgBase'] = $_GET['imgBase'];

    // Image Suffix (if set)
    if ($_POST['imgSuffix'] != '') {
        $data['imgSuffix'] = '_' . $_POST['imgSuffix'];
    } else {
        // -----
        // Get additional images' list; the class function takes care of sorting the files
        //
        $matching_files = array();
        $ih_admin->findAdditionalImages($matching_files, $data['imgBaseDir'], $data['imgExtension'], $data['imgBase']);

        // -----
        // If no additional images exist, use the _01 suffix.
        //
        $file_count = count($matching_files);
        if ($file_count == 1) {
            $data['imgSuffix'] = '_01';
        } else {
            // -----
            // Otherwise, find the first unused suffix in the range _01 to _99.  Note that the first
            // (ignored) element of the find-array "should be" the main image's name!
            //
            for ($suffix = 1, $found = false; $suffix < 99; $suffix++) {
                $suffix_string = sprintf('_%02u', $suffix);
                if (!in_array($data['imgBase'] . $suffix_string . $data['imgExtension'], $matching_files)) {
                    $found = true;
                    $data['imgSuffix'] = $suffix_string;
                    break;
                }
            }
            if (!$found) {
                $messageStack->add('Could not find an unused additional-image suffix in the range _01 to _99.', 'error');
                $data_ok = false;
            }
        }
    }
}

// determine the filenames 
if ($data_ok) {
    // add slash to base dir
    if ($data['imgBaseDir'] != '') {
        if (substr($data['imgBaseDir'], -1) != '/' && substr($data['imgBaseDir'], -1) != '\\') {
            $data['imgBaseDir'] .= '/';
        }
    }
    $data['defaultFileName'] = $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . $data['imgExtension'];

    // Check if the file already exists
    if ($editing && file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . $data['defaultFileName'])) {
        $messageStack->add(TEXT_MSG_FILE_EXISTS, 'error' );
        $data_ok = false;
    }
}

// -----
// If no previous errors and we're either (a) creating a new main-image or (b) editing the main-image and a new name
// is requested ...
//
if ($data_ok && $new_image || ($editing && $main_image && !$keep_name && $_FILES['default_image']['name'] != '')) {
    // -----
    // ... first, check to see that the image's name is going to fit into the database field.
    //
    if (strlen($data['defaultFileName']) > zen_field_length(TABLE_PRODUCTS, 'products_image')) {
        $messageStack->add(sprintf(TEXT_MSG_NAME_TOO_LONG_ERROR, $data['defaultFileName'], zen_field_length(TABLE_PRODUCTS, 'products_image')), 'error');
        $data_ok = false;
    } else {
        // update the database
        $sql = 
            "UPDATE " . TABLE_PRODUCTS . " 
                SET products_image = '" . $data['defaultFileName'] . "' 
              WHERE products_id = " . (int)$products_filter . "
              LIMIT 1";
        if (!$db->Execute($sql)) {
            $messageStack->add(TEXT_MSG_INVALID_SQL, "error");
            $data_ok = false;
        }
    }
}

if ($data_ok) {
    // check for destination directory and create, if they don't exist!
    // Then move uploaded file to its new destination

    // default image
    if ($_FILES['default_image']['name'] != '') {
        io_makeFileDir(DIR_FS_CATALOG_IMAGES . $data['defaultFileName']);
        $source_name = $_FILES['default_image']['tmp_name'];
        $destination_name = DIR_FS_CATALOG_IMAGES . $data['defaultFileName'];
        if (!move_uploaded_file($source_name, $destination_name)) {
            $messageStack->add(TEXT_MSG_NOUPLOAD_DEFAULT, "error" );
            $data_ok = false;
        }
    } elseif ($_FILES['default_image']['name'] == '' && !$editing) {
        // Nigel Hack for special idiots  
        io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['defaultFileName']);
        $source_name = $_FILES['default_image']['tmp_name'];
        $destination_name = DIR_FS_CATALOG_IMAGES . $data['defaultFileName'];
        if (!move_uploaded_file($source_name, $destination_name) ) {
            $messageStack->add( 'you must select a default image', "error" );
            $data_ok = false;
            $_FILES['medium_image']['name'] = $_FILES['large_image']['name'] = '';
        }
    }  // End special idiots hack
    // medium image
    if ($_FILES['medium_image']['name'] != '') {
        $data['mediumImgExtension'] = substr( $_FILES['medium_image']['name'], strrpos($_FILES['medium_image']['name'], '.'));
        $data['mediumFileName'] ='medium/' . $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . IMAGE_SUFFIX_MEDIUM . $data['mediumImgExtension'];
        io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['mediumFileName']);
        $source_name = $_FILES['medium_image']['tmp_name'];
        $destination_name = DIR_FS_CATALOG_IMAGES . $data['mediumFileName'];
        if (!move_uploaded_file($source_name, $destination_name)) {
            $messageStack->add( TEXT_MSG_NOUPLOAD_MEDIUM, "error" );
            $data_ok = false;
        }
    }
    // large image
    if ($_FILES['large_image']['name'] != '') {
        $data['largeImgExtension'] = substr( $_FILES['large_image']['name'], strrpos($_FILES['large_image']['name'], '.'));
        $data['largeFileName'] = 'large/' . $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . IMAGE_SUFFIX_LARGE . $data['largeImgExtension'];
        io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['largeFileName']);
        $source_name = $_FILES['large_image']['tmp_name'];
        $destination_name = DIR_FS_CATALOG_IMAGES . $data['largeFileName'];
        if (!move_uploaded_file($source_name, $destination_name)) {
            $messageStack->add( TEXT_MSG_NOUPLOAD_LARGE, "error" );
            $data_ok = false;
        }
    }  
}

if (!$data_ok) {
    if ($editing) {
        $action = "layout_edit";
    } else {
        $action = "layout_new";
    }
} else {
    // Data has been saved
    // show the new image information
    $messageStack->add(TEXT_MSG_IMAGE_SAVED, 'success');
    echo json_encode(array("products_image"=>$data['defaultFileName'], "asHtml" => '<div class="alert alert-info update-notice update-'.$products_filter.'"><strong>Product image updated</strong></div>'));
    // we might need to clear the cache if filenames are kept
    if ($editing) {
        $error = bmz_clear_cache();
        if (!$error) {
            $messageStack->add(IH_CACHE_CLEARED, 'success');
        }
    }
    $_GET['imgName'] = $data['imgBase'] . $data['imgSuffix'];
    $action = "layout_info";
}

}

我要说的一点是,在开发人员工具中查看控制台日志时,它突出显示了表单所在文件的第一个字符,而不是json_encode所在的文件。代码结构的格式为文件A,它在文件B中起作用。文件B包含我要发送的json_encode响应,但错误显示文件A的html内容以及子数据。它的一个片段在这里。

{"products_image":"Teal-Shirt-min_01.jpg","asHtml":"<div class=\"alert alert-info update-notice update-310\"><strong>Product image updated<\/strong><\/div>"}
<div class="container-fluid">
    <div id="ih-head">
        <h1>Image Handler<sup>5</sup></h1>
    </div>


    <div id="defaultContent">
        <div class="row">
            <div class="col-md-6 col-sm-12 no-padding">
                <div class="ih-heading pull-left">Product</div>
                <div class="ih-info pull-left">&nbsp;#310 &mdash; Teal T-Shrt</div>
            </div>
            <div class="col-md-6 col-sm-12 no-padding">
                <div class="ih-heading pull-left">Image Directory</div>
                <div class="ih-info pull-left">&nbsp;images/</div>  
            </div>
        </div>
        <hr>

1 个答案:

答案 0 :(得分:0)

鉴于您正在返回当前页面的内容,我想您的ajax请求设置不正确。

“ url”应设置为要处理数据并返回响应的脚本的url。如果未设置“ URL”,则默认为“当前URL”。

所以我认为您想要以下类似的网址...

.ajax({
      url: "/myapp/myJsonResponseScript.php",
   ....

在ajax调用的数据选项中传递您的操作值。