繁体   English   中英

如何以 JSON Object 的形式发送表单数据?

[英]How to send form-data as a JSON Object..?

我的服务器端有一些文本输入和图像。 我需要将此数据作为 JSON object 发送。 但由于 FormData,我无法发送这样的图像。所以我需要将我的表单数据转换为一个 JSON object。 请帮助我...谢谢...!

HTML 部分 -

    <form>
        <div class="form-group">
            <label for="txtcustomerImage"> <i class="tags icon"></i> Image Of Your NIC</label>
            <input class="form-control-file" id="txtcustomerImage" type="file" name="txtcustomerImage">
            </div>
    </form>

Ajax 零件 -

$('#btnCreateNewAccount').click(function () {


    var fileObject = $("#txtcustomerImage")[0].files[0];//access file object from input field
    var fileName = $("#txtcustomerImage")[0].files[0].name; //get file name
    var form = new FormData(); //setup form data object to send file data
    form.append("custImage", fileObject, fileName); //append data



    console.log('clicked..');
    let customerNIC = $('txtcustomerNIC').val();
    let customerName = $('txtcustomerName').val();
    let customerAddress = $('txtcustomerAddress').val();

    console.log(form)

    $.ajax({
        method: "post",
        url: "http://localhost:8080/Sprinf_Final-Back-end/customer",
        contentType: "application/json",
        data: JSON.stringify({
            customerNIC: customerNIC,
            customerName: customerName,
            customerAddress: customerAddress,

        }),
        success: function (res) {
            if (res.massage == 'Success') {
                alert('Your Account is Successfully Created!When You Log to Server Use Your User Name & Password..!');
                console.log(res);
            } else {
                console.log('error');
            }
        }
    });

});

如果您想将数据作为 JSON 发送,那么创建FormData object 是没有意义的。 您可以使用fileObject.text()读取文件内容并将其发送:

 $('#btnCreateNewAccount').click(async function() { const fileObject = $("#txtcustomerImage")[0].files[0]; //access file object from input field const fileName = fileObject.name; //get file name const data = JSON.stringify({ fileObject: await fileObject.text(), fileName }) console.log(data); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <div class="form-group"> <label for="txtcustomerImage"> <i class="tags icon"></i> Image Of Your NIC</label> <input class="form-control-file" id="txtcustomerImage" type="file" name="txtcustomerImage"> </div> </form> <button id="btnCreateNewAccount"> Click </button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM