如何在另一页上获取div项目的数据属性

时间:2019-05-10 18:46:31

标签: php html ajax

我正在使用超薄图像裁剪器。

我有以下内容。

<div class="slim" data-service="async.php" data-ratio="3:2" data-size="600,400" data-row="">
                        <!-- <input type="hidden" id="rowID" name="rowID"> -->
                        <input type="file"/>
                    </div>

我添加了data-row =“”,然后在jquery中添加了以下内容。

$('.slim').attr('data-row', rowID);

那部分工作正常,但是现在我该如何收回async.php页上的数据行的值?

这是ASYNC.php

            <?php

        // Uncomment if you want to allow posts from other domains
        // header('Access-Control-Allow-Origin: *');

        require_once('slim.php');

        foreach(Slim::getImages() as $imagess) {
            echo $imagess['meta']->data-row;
        }
        // Get posted data, if something is wrong, exit
        try {
            $images = Slim::getImages();
        }
        catch (Exception $e) {

            // Possible solutions
            // ----------
            // Make sure you're running PHP version 5.6 or higher

            Slim::outputJSON(array(
                'status' => SlimStatus::FAILURE,
                'message' => 'Unknown'
            ));

            return;
        }

        // No image found under the supplied input name
        if ($images === false) {

            // Possible solutions
            // ----------
            // Make sure the name of the file input is "slim[]" or you have passed your custom
            // name to the getImages method above like this -> Slim::getImages("myFieldName")

            Slim::outputJSON(array(
                'status' => SlimStatus::FAILURE,
                'message' => 'No data posted'
            ));

            return;
        }

        // Should always be one image (when posting async), so we'll use the first on in the array (if available)
        $image = array_shift($images);

        // Something was posted but no images were found
        if (!isset($image)) {

            // Possible solutions
            // ----------
            // Make sure you're running PHP version 5.6 or higher

            Slim::outputJSON(array(
                'status' => SlimStatus::FAILURE,
                'message' => 'No images found'
            ));

            return;
        }

        // If image found but no output or input data present
        if (!isset($image['output']['data']) && !isset($image['input']['data'])) {

            // Possible solutions
            // ----------
            // If you've set the data-post attribute make sure it contains the "output" value -> data-post="actions,output"
            // If you want to use the input data and have set the data-post attribute to include "input", replace the 'output' String above with 'input'

            Slim::outputJSON(array(
                'status' => SlimStatus::FAILURE,
                'message' => 'No image data'
            ));

            return;
        }



        // if we've received output data save as file
        if (isset($image['output']['data'])) {

            // get the name of the file
            $name = $image['output']['name'];

            // get the crop data for the output image
            $data = $image['output']['data'];

            // If you want to store the file in another directory pass the directory name as the third parameter.
            // $output = Slim::saveFile($data, $name, 'my-directory/');

            // If you want to prevent Slim from adding a unique id to the file name add false as the fourth parameter.
            // $output = Slim::saveFile($data, $name, 'tmp/', false);

            // Default call for saving the output data
            $output = Slim::saveFile($data, $name, 'images/modules/listings');
        }

        // if we've received input data (do the same as above but for input data)
        if (isset($image['input']['data'])) {

            // get the name of the file
            $name = $image['input']['name'];

            // get the crop data for the output image
            $data = $image['input']['data'];

            // If you want to store the file in another directory pass the directory name as the third parameter.
            // $input = Slim::saveFile($data, $name, 'my-directory/');

            // If you want to prevent Slim from adding a unique id to the file name add false as the fourth parameter.
            // $input = Slim::saveFile($data, $name, 'tmp/', false);

            // Default call for saving the input data
            $input = Slim::saveFile($data, $name, 'images/modules/listings');

        }



        //
        // Build response to client
        //
        $response = array(
            'status' => SlimStatus::SUCCESS
        );

        if (isset($output) && isset($input)) {

            $response['output'] = array(
                'file' => $output['name'],
                'path' => $output['path']
            );

            $response['input'] = array(
                'file' => $input['name'],
                'path' => $input['path']
            );

        }
        else {
            $response['file'] = isset($output) ? $output['name'] : $input['name'];
            $response['path'] = isset($output) ? $output['path'] : $input['path'];
        }

        // Return results as JSON String

        Slim::outputJSON($response);

这是SLIM.php

        <?php


    abstract class SlimStatus {
        const FAILURE = 'failure';
        const SUCCESS = 'success';
    }

    class Slim {

        public static function getImages($inputName = 'slim') {

            $values = Slim::getPostData($inputName);

            // test for errors
            if ($values === false) {
                return false;
            }

            // determine if contains multiple input values, if is singular, put in array
            $data = array();
            if (!is_array($values)) {
                $values = array($values);
            }

            // handle all posted fields
            foreach ($values as $value) {
                $inputValue = Slim::parseInput($value);
                if ($inputValue) {
                    array_push($data, $inputValue);
                }
            }

            // return the data collected from the fields
            return $data;

        }

        // $value should be in JSON format
        private static function parseInput($value) {

            // if no json received, exit, don't handle empty input values.
            if (empty($value)) {return null;}

            // If magic quotes enabled
            if (get_magic_quotes_gpc()) {
                $value = stripslashes($value);
            }

            // The data is posted as a JSON String so to be used it needs to be deserialized first
            $data = json_decode($value);

            // shortcut
            $input = null;
            $actions = null;
            $output = null;
            $meta = null;

            if (isset ($data->input)) {

                $inputData = null;
                if (isset($data->input->image)) {
                    $inputData = Slim::getBase64Data($data->input->image);
                }
                else if (isset($data->input->field)) {
                    $filename = $_FILES[$data->input->field]['tmp_name'];
                    if ($filename) {
                        $inputData = file_get_contents($filename);
                    }
                }

                $input = array(
                    'data' => $inputData,
                    'name' => $data->input->name,
                    'type' => $data->input->type,
                    'size' => $data->input->size,
                    'width' => $data->input->width,
                    'height' => $data->input->height,
                );

            }

            if (isset($data->output)) {

                $outputDate = null;
                if (isset($data->output->image)) {
                    $outputData = Slim::getBase64Data($data->output->image);
                }
                else if (isset ($data->output->field)) {
                    $filename = $_FILES[$data->output->field]['tmp_name'];
                    if ($filename) {
                        $outputData = file_get_contents($filename);
                    }
                }

                $output = array(
                    'data' => $outputData,
                    'name' => $data->output->name,
                    'type' => $data->output->type,
                    'width' => $data->output->width,
                    'height' => $data->output->height
                );
            }

            if (isset($data->actions)) {
                $actions = array(
                    'crop' => $data->actions->crop ? array(
                        'x' => $data->actions->crop->x,
                        'y' => $data->actions->crop->y,
                        'width' => $data->actions->crop->width,
                        'height' => $data->actions->crop->height,
                        'type' => $data->actions->crop->type
                    ) : null,
                    'size' => $data->actions->size ? array(
                        'width' => $data->actions->size->width,
                        'height' => $data->actions->size->height
                    ) : null,
                    'rotation' => $data->actions->rotation,
                    'filters' => $data->actions->filters ? array(
                        'sharpen' => $data->actions->filters->sharpen
                    ) : null
                );
            }

            if (isset($data->meta)) {
                $meta = $data->meta;
            }

            // We've sanitized the base64data and will now return the clean file object
            return array(
                'input' => $input,
                'output' => $output,
                'actions' => $actions,
                'meta' => $meta
            );
        }

        // $path should have trailing slash
        public static function saveFile($data, $name, $path = 'tmp/', $uid = true) {

            // Add trailing slash if omitted
            if (substr($path, -1) !== '/') {
                $path .= '/';
            }

            // Test if directory already exists
            if(!is_dir($path)){
                mkdir($path, 0755, true);
            }

            // Sanitize characters in file name
            $name = Slim::sanitizeFileName($name);

            // Let's put a unique id in front of the filename so we don't accidentally overwrite other files
            if ($uid) {
                $name = uniqid() . '_' . $name;
            }

            // Add name to path, we need the full path including the name to save the file
            $path = $path . $name;

            // store the file
            Slim::save($data, $path);

            // return the files new name and location
            return array(
                'name' => $name,
                'path' => $path
            );
        }

        /**
         * Get data from remote URL
         * @param $url
         * @return string
         */
        public static function fetchURL($url, $maxFileSize) {
            if (!ini_get('allow_url_fopen')) {
                return null;
            }
            $content = null;
            try {
                $content = @file_get_contents($url, false, null, 0, $maxFileSize);
            } catch(Exception $e) {
                return false;
            }
            return $content;
        }

        public static function outputJSON($data) {
            header('Content-Type: application/json');
            echo json_encode($data);
        }

        /**
         * http://stackoverflow.com/a/2021729
         * Remove anything which isn't a word, whitespace, number
         * or any of the following characters -_~,;[]().
         * If you don't need to handle multi-byte characters
         * you can use preg_replace rather than mb_ereg_replace
         * @param $str
         * @return string
         */
        public static function sanitizeFileName($str) {
            // Basic clean up
            $str = preg_replace('([^\w\s\d\-_~,;\[\]\(\).])', '', $str);
            // Remove any runs of periods
            $str = preg_replace('([\.]{2,})', '', $str);
            return $str;
        }

        /**
         * Gets the posted data from the POST or FILES object. If was using Slim to upload it will be in POST (as posted with hidden field) if not enhanced with Slim it'll be in FILES.
         * @param $inputName
         * @return array|bool
         */
        private static function getPostData($inputName) {

            $values = array();

            if (isset($_POST[$inputName])) {
                $values = $_POST[$inputName];
            }
            else if (isset($_FILES[$inputName])) {
                // Slim was not used to upload this file
                return false;
            }

            return $values;
        }

        /**
         * Saves the data to a given location
         * @param $data
         * @param $path
         * @return bool
         */

        private static function save($data, $path) {
            if (!file_put_contents($path, $data)) {
                return false;
            }

            return true;
        }

        /**
         * Strips the "data:image..." part of the base64 data string so PHP can save the string as a file
         * @param $data
         * @return string
         */
        private static function getBase64Data($data) {
            return base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
        }

    }

所有页面都包括在内,我不确定在哪里添加它,这样我就可以检索到该rowID,是在异步还是苗条下。对困惑感到抱歉。希望添加这些页面有助于清除一些内容。

2 个答案:

答案 0 :(得分:0)

您的HTML可以保持不变。

<div class="slim" data-service="async.php" data-ratio="3:2" data-size="600,400">
    <input type="file" />
</div>

在您的JS中附加data-meta-data-row也包含rowID

(['data-meta-data-row', 'data-row']).forEach( (key) => {
    $('.slim').attr(key, rowID);
});

然后在服务器端,您可以使用meta键,该键包含如下属性的对象:

foreach(Slim::getImages() as $image)
    echo $image['meta']->data-row;

答案 1 :(得分:0)

因此,经过大量黑客攻击。我在苗条的框架开发人员的帮助下找到了答案。 根据文档,有一个名为willSave的函数,可以触发该函数,并且只要在服务器上调用该函数就会更新。

slim的元数据仅在页面加载时调用,这就是为什么当通过我的自定义函数更新变量时它从未读取的原因。

我的解决方法如下:

打开模态后,我创建了will save函数。我将变量从打开模式的函数传递到保存函数。

下面的代码仅供参考,并向开发人员大声疾呼以寻求初始帮助。

html

<div id="slim" class="slim" data-service="async.php" data-ratio="3:2" data-size="600,400" data-will-save="saveRow">
  <input type="file"/>
 </div>

JS

    function addThumb(rowID) {
    //$('.slim').attr('data-meta-data-row', rowID);
    window.row = rowID;
    $("#imageManager").modal('show');
}

function saveRow(data, ready) {
    data.meta.row = window.row;
    ready(data);
}