duan1443 2019-05-10 18:46
浏览 356

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

I am using slim image cropper.

I have the following.

<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>

I added the data-row=" " and then in the jquery I added the following.

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

That part is working fine, but now how do I retireve the value of the data-row on the async.php page?

Here is 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);

Here is the 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));
        }

    }

That is all the pages includes, I am not sure where to even add this so I can retrieve this rowID, is it under the async, or the slim. Sorry for the confusion. Hopefully adding these pages helped clear some stuff up.

  • 写回答

2条回答 默认 最新

  • douxun4173 2019-05-10 19:06
    关注

    Your HTML can stay the same.

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

    Append data-meta-data-row to contain the rowID as well in your JS.

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

    On the server side, you can then use the meta key which holds an object of properties like so:

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

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致