在使用jquery提交表单之前添加自定义$ _POST

时间:2017-08-08 21:23:32

标签: php jquery form-submit

首先,对不起,如果这是重复的话。我看了看并找到了一些解决方案,但都没有效果。我一直试图做这个简单的事情,就像3个小时一样没有结果。

我有这个HTML:

<form method="post" action="?c=Logo&action=save" id="form">
    <!-- some inputs -->
    <img src="" data-filename="new-logo.png">
    <input type="submit" value="submit">
</form>

在这里,我想修改表单,以便我的php文件识别$ _POST ['new-logo']。

// $_POST['new-logo'] =  $('img').data('filename')
$logo = new Logo($_POST['new-logo']); 
$logo->save();

我想我应该使用jQuery函数$ .post()但不知何故我无法管理。谢谢大家的帮助: - )


最后,因为我找到了一个非常简单的解由于我希望我的数据在我的php文件中处理,我只需添加一个<input type="hidden">并用JS修改它的值: - )

4 个答案:

答案 0 :(得分:0)

你也可以像这样从头创建数据数组:

$('#form').on('submit', function(e){
    e.preventDefault();

    $.ajax({
       type: "POST",
       url: $(this).attr('action'),
       data: {key1:"value", key2:"value2"},
       dataType: "json",
       success: function(data) {
           //do success stuff here
       },
       error: function() {
           //do error stuff here.
       }
    });
});

答案 1 :(得分:0)

您可以将其添加为隐藏输入。

$("#form").submit(function() {
    $(this).append($("<input>", {
        type: "hidden",
        name: "new-logo",
        value: $(this).find("img").data("filename")
    });
});

答案 2 :(得分:0)

您可以将此添加到您发布请求,如下所示:

$('#form').on('submit', function(e){
    e.preventDefault();

    var $form = $(this);

    var datastring = $form.serializeArray();
    datastring.push({name:'new-logo', value:$form.find('img').data('filename')});

    $.ajax({
       type: "POST",
       url: $form.attr('action'),
       data: datastring,
       dataType: "json",
       success: function(data) {
           //var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
           // do what ever you want with the server response
       },
       error: function() {
           alert('error handing here');
       }
    });
});

答案 3 :(得分:-1)

        $logo = new Logo($_POST['new-logo']); 

“新标识”是一种功能还是什么?很确定没有空间。

相关问题