【问题标题】:jquery send hidden input via ajaxjquery通过ajax发送隐藏输入
【发布时间】:2019-12-22 04:25:30
【问题描述】:

我试图通过 ajax 发送数据

$('#myForm').submit(function() {
    // Get all the forms elements and their values in one step
    var values = $(this).serialize();

});

这个表格只有hidden input tags with values这样的

    <input type="hidden" value="'.$post_by_user.'" name="posted_by" />
  <input type="hidden" value="like" name="like_button" />

如何在点击div="send" 时发送表单而不提交表单?还有其他方法吗?

我正在尝试的另一种方法

<script>
$(document).ready(function() {
  $("#like").click(function(e) {
    e.preventDefault();
       var post_info = $("#post_info :input").serialize();
    $.post("like.php", post_info).done(function(data) {
      $("#like").html(data);
    }).fail(function() {
      //alert("Error");
    })
  })
})
</script>

【问题讨论】:

  • 你的意思是serialize()?序列化适用于隐藏字段。你试过了吗?
  • 是的,序列化隐藏的输入并通过 post 发送
  • 对,serialize() 已经这样做了。那么问题是什么?
  • 查看我的问题更新,不知何故它没有发送数据做后端
  • $("#post_info :input").serialize(); 的结果是什么?

标签: jquery html ajax forms post


【解决方案1】:

$.serialize() 准备一个适合GET 请求的数据字符串。如果要使用POST 请求,则应使用$.serializeArray(),如下所示:

$('#frm1').submit(function(e){
    e.preventDefault();
    var vals = $(this).serializeArray();  // prepare a data object
    $.post("https://jsonplaceholder.typicode.com/posts", vals)
     .done(function(data) {  // display the server response:
        console.log("posted:",JSON.stringify(data));
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<form id="frm1">
  Here is the form with invisible fields<br>
  <input type="hidden" value="one" name="var1" />
  <input type="hidden" value="two" name="var2" />
  <input type="hidden" value="three" name="var3" />
  <input type="submit" value="send in background" id="btn">
</form>

【讨论】:

  • 我只注意到我回答了一个四年前的问题...... :D - 抱歉制造了这么多噪音! :D :D
【解决方案2】:

这样序列化并使用ajax

     var frm1 = $(document.myForm);
     var jdata = JSON.stringify(frm1.serializeArray());
      $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json",
                    url: "Your URL",
                    data: JSON.stringify({ sdata: jdata}),
                    success: function (result) {
                    }
                }); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2020-09-20
    • 2013-08-18
    • 1970-01-01
    相关资源
    最近更新 更多