How to submit a form with AJAX/JSON?

后端 未结 4 915
温柔的废话
温柔的废话 2020-12-18 08:24

Currently my AJAX is working like this:

index.php

One    
相关标签:
4条回答
  • 2020-12-18 08:30

    Here is my complete solution:

    jQuery('#myForm').live('submit',function(event) {
        $.ajax({
            url: 'one.php',
            type: 'POST',
            dataType: 'json',
            data: $('#myForm').serialize(),
            success: function( data ) {
                for(var id in data) {
                    jQuery('#' + id).html(data[id]);
                }
            }
        });
        return false;
    });
    
    0 讨论(0)
  • 2020-12-18 08:35

    Submitting the form is easy:

    $j('#myForm').submit();
    

    However that will post back the entire page.

    A post via an Ajax call is easy too:

    $j.ajax({
        type: 'POST',
        url: 'one.php',
        data: { 
            myText: $j('#myText').val(), 
            myButton: $j('#myButton').val()
        },
        success: function(response, textStatus, XMLHttpRequest) {  
            $j('div.ajax').html(response);
        }
    });
    

    If you then want to do something with the result you have two options - you can either explicitly set the success function (which I've done above) or you can use the load helper method:

    $j('div.ajax').load('one.php', data);
    

    Unfortunately there's one messy bit that you're stuck with: populating that data object with the form variables to post.

    However it should be a fairly simple loop.

    0 讨论(0)
  • 2020-12-18 08:43

    Have a look at the $.ajaxSubmit function in the jQuery Form Plugin. Should be as simple as

     $('#myForm').ajaxSubmit();
    

    You may also want to bind to the form submit event so that all submissions go via AJAX, as the example on the linked page shows.

    0 讨论(0)
  • 2020-12-18 08:49

    You can submit the form with jQuery's $.ajax method like this:

    $.ajax({
     url: 'one.php',
     type: 'POST',
     data: $('#myForm').serialize(),
     success:function(data){
       alert(data);
     }
    });
    
    0 讨论(0)
提交回复
热议问题