javascript - 在 PHP 中编码 JSON 并使用 POST 提交

标签 javascript php jquery ajax json

问题:

我有一个用 JSON 编码的变量,我一直在尝试弄清楚如何使用 jQuery/AJAX 将这个变量发送到 PHP 页面。

这是我到目前为止尝试过的。

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

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["透视"]

此外,OE.lc 检查表单是否使用以下方式提交:

$_POST["form_submitted"]

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

有什么想法吗?

最佳答案

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

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

$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();
        },
        // ...
    });

请告诉我这是否适合您!

关于javascript - 在 PHP 中编码 JSON 并使用 POST 提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20071215/

相关文章:

javascript - 无法使用 jQuery 定位多个单词

javascript - 如何在 Node.js 中与 Net 建立持久连接?

php - echarts:从URL获取数据

jQuery UI 自动完成不会将隐藏的输入新值发送到 script_url

PHPExcel如何在设置样式后取消选择列或范围

php - 将 mysql 查询的结果获取到整数数组中?

Javascript 正则表达式替换,多行

javascript - ES6 生成器 : why the argument passed to the first next() function doesn't work?

javascript - 哪些 Parsely 配置选项为错误/成功设置 CSS 类?

javascript - 创建切换按钮以在 div 面板之间切换