如何在ajax javascript中以json格式将表单数据发送到服务器

时间:2014-01-15 11:31:11

标签: javascript jquery ajax json

function ajax() {
  $('form').submit(function() {
    console.log($(this).serializeArray());
    $('#result').text(JSON.stringify($(this).serializeArray()));
    return false;
  });
}

这是我得到的json数据:

[{"name":"firstName","value":"erere"},{"name":"lastName","value":"rere"},{"name":"emailAddress","value":"eregedfd@gmail.com"},{"name":"password","value":"dfdfd"},{"name":"phoneNumber","value":"989989898"}]

如何将其发送到服务器。我应该在ajax调用中包含哪些数据?

2 个答案:

答案 0 :(得分:3)

一个简单的例子:

$('form').submit(function() {

    $.post( "send.php", $(this).serializeArray())
      .done(function( reply ) {
        alert( "Complete, reply from server: " + reply );
      });

    return false;
});

有关处理回调的信息,请参阅:http://api.jquery.com/jquery.post/

答案 1 :(得分:2)

试试这个:

$('form').submit(function() {
    var form = $(this);
    var data = form.serialize();

    $.ajax({
        url: 'post url'
        method: 'POST',
        data: data,
        success: function(resp){
             //action on successful post
        },
        error: function() {
            //handle error
        }
    });
    return false;
});