在确认提交到服务器

时间:2017-05-10 10:01:49

标签: php jquery forms post preview

我的页面包含许多字段和图像的表单:

<form method="POST" action="http://project.dev/model/useradd" accept-charset="UTF-8" autocomplete="off" id="AddModel" enctype="multipart/form-data">
<input name="_token" type="hidden" value="yeq4iLVIyXiYyMbORaY5fA6zxIYDFWNJTqNVYiP9">   
<div class="form-group">
    <label for="material">Material</label>
    <input type="text" class="form-control" name="material" maxlength="30" style="width:30ch">
</div>
<div class="form-group">
    <label for="color">Color</label>
    <input type="text" class="form-control" name="color" maxlength="10" style="width:20ch">
</div>
<div class="form-group">
    <label for="description">Description</label>
    <input type="text" class="form-control" name="description" maxlength="500">
</div>
<div class="form-group">
    <label for="image">Picture</label>
    <input id="modelpic" name="image" type="file">
    <br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show the preview of the image through javascript */
<div class="form-group">
    <input id="AddBtn" class="btn btn-default" type="submit" value="Submit">
</form>

这里是javascript,它在选择后显示表单中的图像预览:

    $(document).ready(function() {
    $('#modelpic').on("change", function () {

        //shows image preview in DOM
        var files = !!this.files ? this.files : [];

        if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support

        if (/^image/.test( files[0].type)){ // only image file
            var reader = new FileReader(); // instance of the FileReader
            reader.readAsDataURL(this.files[0]); // read the local file

            reader.onloadend = function(){ // show image in div
                $('#imagePreview').show().html('<img id="theImage" src="' +this.result+ '" class="img-fluid" alt="Your Image" />');

            }
        }
    })
});

我需要做的是在确认提交之前显示该帖子的预览。 我怎么能用jquery做到这一点?我的猜测是我还必须将html中的表单代码action="http://project.dev/model/useradd"的操作部分修改为类似self或者其他东西的东西?这是对的吗? 如何在jquery中点击提交后获取提交的表单数据并使用它将html输出到预览div?

---我还想到将数据发送到服务器,暂时将图像保存在公共场所,然后将其加载到预览中。问题是,如果我使用ajax拦截提交,则不提交图像。我认为这是一个规范数据的问题。我的JS脚本代码是这样的:

jQuery(function ($) {
    $(document).ready(function () {

        $("body").on("submit", "#AddModel", function (e) {

            var form = $(this);

            $.ajax({
                url: form.prop('action'),
                type: 'post',
                dataType: 'json',
                data: $(this).serialize(),
                success: function (data) {

                console.log(data);


                },
                error: function (textStatus) {

                    {


                        var json = JSON.parse(textStatus.responseText);


                        console.log (json);


                    }

                }
            });
            e.preventDefault();
        });
    });
});

我认为这可能是数据类型中的错误。

0 个答案:

没有答案