duangan6797 2017-05-05 00:02
浏览 103
已采纳

通过jquery发送请求发送按钮值

My code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<form>
<button id="test" value="123" name="test" >ok</button>
</form>

<script>


 $(document).ready(function () {
          $("#test").click(function() {
                   var combinedData = $("#test").serialize();
                 $.post(
                        "element_submit.php",
                        combinedData
                 ).done(function(data) {
                        //alert("Successfully submitted!");
                        $("#result").html(data);
                 }).fail(function () {
                          //alert("Error submitting forms!");
                 })
          });
        });

</script>



<div id="result" ></div>

The element_submit.php file

<?php 

//just to test it should output in the #result div 
echo $_POST['test'];

?>

What I am trying to do is submit the with the value="attribute" so the data is serialized and send the post request, it's not like a submit when user insert a value and submit,What I need is to get the value attribute and submit to the php, this code is only for To simplify and illustrate what I am trying to do, because in this page I have the following buttons with ids #follow #unfollow so I need a way to get the button value to make the user follow and unfollow.

  • 写回答

2条回答 默认 最新

  • douyan9398 2017-05-05 00:10
    关注

    you need to serialize the form - not the elements within it .You can also have the triggering button outside the form which will prevent hte form from submitting on the button click.

    <form id="testForm">
       <input type="hidden" name="testInput" value="123"/>
    </form>
    
     <button name="test" id="testButton">submit</button>
    ...
    
    <script>
     $(document).ready(function () {
              $("#testButton").click(function() {
                       var combinedData = $("#testForm").serialize();...
    

     $(document).ready(function () {
        $("#testButton").click(function() {
            var combinedData = $("#testForm").serialize();
             console.log(combinedData);
          })
       })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="testForm">
       <input type="hidden" value="123" name="testinput"/>
    </form>
    <button  id="testButton">Click</button>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?