在PHP中对JSON进行编码并使用POST提交


Encode JSON in PHP and submit with POST

问题:

我有一个用JSON编码的变量,我一直在想如何使用jQuery/AAJAX将这个变量发送到PHP页面。

这就是我迄今为止所尝试的。

  1. 文件上载使用http://blueimp.github.io/jQuery-File-Upload/
  2. 它由jQuery根据下面的JS代码进行处理

JS代码:

<script>    
    $(function () {
        'use strict';
        // Server-side upload handler:
        var url = 'process.php';
        $('#fileupload').fileupload({
            url: url,
            autoUpload: true,
            acceptFileTypes: /('.|'/)(txt)$/i,
            maxFileSize: 5000000, // 5 MB               
            done: function (e, data) {
                setTimeout(function(){
                    $("#loading").html("Loading...");}, 1000);
                var formUrl = 'exec.php',
                // You'll have to re-encode to JSON, probably:
                formPerspective = JSON.stringify(data.result.formPerspective),
                // This is the newly added value ( Maybe this needs JSON aswell? )
                formTxtfile = JSON.stringify(data.result.formTxtfile),
                // Generate the form
                $form = $('<form action="'+ formUrl +'" method="post"></form>')
                        .append('<input type="hidden" name="Perspective" value="' + formPerspective + '">')
                        .append('<input type="hidden" name="Datafile" value="' + formTxtfile + '">')
                        .append('<input type="hidden" name="form_submitted">');
                // Submit the form
                $form.submit();
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css(
                    'width',
                    progress + '%'
                );
            }
        }).prop('disabled', !$.support.fileInput)
            .parent().addClass($.support.fileInput ? undefined : 'disabled');
    });
</script>
  1. 正如您所看到的,它根据下面的代码调用PHP处理程序

PHP代码:

<?php
    session_start();
    $folder      = 'upload';
    if (!empty($_FILES))
    {
        // Set temporary name
        $tmp    = $_FILES['files']['tmp_name'];
        // Set target path and file name
        $target = $folder . '/' . $_FILES['files']['name'];
        // Upload file to target folder
        $status = move_uploaded_file($tmp, $target);
        if ($status)
        {
            // Set session with txtfile name
            $_SESSION['txtfile']    = $_FILES['files']['name'];
            $text_file    = file('upload/' . $_SESSION['txtfile']);
            foreach ($text_file as $line_number => $line)
            {               
                if (strpos($line, "'t") === 0)
                {
                    // Remove commented column names and first 't
                    $dimensions = explode("'t", preg_replace("#'t/.+#", '', substr($line, 1)));
                }               
            }
            // Set dimensions
            $_SESSION['dimensions'] = str_replace(''n', '', $dimensions);
            $jsonReturn = array(
                'formPerspective'   => $_SESSION['dimensions'],
                'formTxtfile'       => $_SESSION['txtfile']
            );
            // Convert to JSON
            $encode = json_encode($jsonReturn);
            echo $encode;
        }
    }
?>

所需解决方案:

我想获取$encode中的信息,并使用POST将其发送到页面"oe.lc"。在oe.lc上,使用选择变量

$_POST["Perspective"]

此外,OE.lc会检查表单是否使用提交

$_POST["form_submitted"]

JS应该在提交后重定向到OE.lc(现在它重定向到explorer.php)

有什么想法吗?

尝试简单地回显$encode,然后使用die(); 退出脚本

编辑:您说过要在表单中添加额外的值,首先需要更改php文件,该文件决定返回JSON:中的Javascript

$jsonReturn = array(
    'formPerspective' => $dimensions,
    'formTxtfile' => $_SESSION['txtfile'],
);
// Convert to JSON
$encode = str_replace(''n', '', json_encode($jsonReturn));
// The above will print out the following when echoed:
// {'formPerspective':["legs","skincover","weight","intelligence","speed"], 'formTxtfile': 'Not sure what this holds as data'}
die($encode);

然后,数据应该在您配置的done回调中的data.result中。

你可能想把浏览器转发到oe.lc,你生成一个表单并提交怎么样?

编辑:我们应该在此处添加新累积的值:

$('#fileupload').fileupload({
        // ...
        done: function (e, data) {
                // Determine the url:
            var formUrl = 'http://oe.lc',
                // You'll have to re-encode to JSON, probably:
                formPerspective = JSON.stringify(data.result.formPerspective),
                // This is the newly added value ( Maybe this needs JSON aswell? )
                formTxtfile = JSON.stringify(data.result.formTxtfile),

                // Generate the form
                $form = $("<form action='"+ formUrl +"' method='post'></form>")
                        .append("<input type='hidden' name='Perspective' value='" + formPerspective + "'>")
                        .append("<input type='hidden' name='Datafile' value='" + formTxtfile + "'>")
                        .append("<input type='hidden' name='form_submitted'>")
                        .appendTo('body');
                // Submit the form
                $form.submit();
        },
        // ...
    });

如果这对你有用,请告诉我!

以下是完整的代码(但在Firefox中不起作用):

<script>    
    $(function () {
        'use strict';
        // Server-side PHP upload handler
        var url = 'process.php';
        // File upload handler
        $('#fileupload').fileupload({
            url: url,
            dataType: 'json',
            autoUpload: true,
            acceptFileTypes: /('.|'/)(txt)$/i,
            maxFileSize: 5000000, // 5 MB               
            done: function (e, data) {
                // Output alert message
                setTimeout(function(){
                    $("#loading").html("Loading...");}, 1000);
                // Form destination
                var formUrl = 'test.php',
                // Variables to be sent with the form
                formPerspective = data.result.formPerspective,
                formTxtfile = data.result.formTxtfile,
                // Generate the form
                $form = $("<form action='"+ formUrl +"' method='post'></form>")
                        .append("<input type='hidden' name='Perspective' value='" + formPerspective + "'>")
                        .append("<input type='hidden' name='Datafile' value='" + formTxtfile + "'>")
                        .append("<input type='hidden' name='form_submitted' value='true'>")
                        .appendTo('body');
                // Submit the form
                $form.submit();
            },
            // Progress indicator
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css(
                    'width',
                    progress + '%'
                );
            }
        }).prop('disabled', !$.support.fileInput)
            .parent().addClass($.support.fileInput ? undefined : 'disabled');
    });
</script>