如何通过ajax发送值输入类型文本?

时间:2016-11-15 13:36:20

标签: javascript php jquery ajax

我有这样的输入类型文本

<input type="text" id="test" value="">

我有这样的ajax post功能。

$(document).ready(function() {
    $('#summernote').summernote({
        height: 300,                 // set editor height
        minHeight: null,             // set minimum height of editor
        maxHeight: null,             // set maximum height of editor
        focus: true,                  // set focus to editable area after initializing summernote
        callbacks: {
            onImageUpload: function(files) {
                sendFile(files[0]);
            }
        }
    });   

    function sendFile(file, editor, welEditable) {
        document.getElementById("loading_upload_threads_image").style.display = "block";
        data = new FormData();
        data.append("file", file);//You can append as many data as you want. Check mozilla docs for this
        $.ajax({
            data: data,
            type: "POST",
            url: "threads_image_upload.php",
            cache: false,
            contentType: false,
            processData: false,
            success: function(url) {
                $('#summernote').summernote('editor.insertImage', url);
                document.getElementById("loading_upload_threads_image").style.display = "none";
            }
        });
    }
});

我想知道如何将价值从id="test"发送到我的ajax帖子?

2 个答案:

答案 0 :(得分:4)

您可以使用append()方法将所需的任何数据添加到FormData对象中 - 正如您的评论事件所示。试试这个:

data = new FormData();
data.append("file", file);
data.append('test', $('#test').val());

或者,如果要发送表单中的所有数据,则可以向form构造函数提供FormData元素。请注意,这些项目将以input的名称作为键。

var data = new FormData($('form')[0]);

答案 1 :(得分:2)

你可以这样做:

HTML代码:

<input type="text" id="test" value="">

JS代码:

data = new FormData();
data.append("file", file);
data.append("test", $('#test').val());

$.ajax({
    data: data,
    type: "POST",
    url: "threads_image_upload.php",
    cache: false,
    contentType: false,
    processData: false,
    success: function(url) {
        $('#summernote').summernote('editor.insertImage', url);
        document.getElementById("loading_upload_threads_image").style.display = "none";
    }
});

在PHP中,您可以访问它:

$test = $_POST['test'];

希望这有帮助!

相关问题