使用jQuery .ajax以JSON的形式提交数据

时间:2014-06-03 01:24:01

标签: jquery ajax json

我已经在这几天了,并且无法做到这一点。我试图将表单数据作为JSON提交给Web服务。我已经尝试过显式设置键值对,例如

data : JSON.stringify({
            type: $('#type').val(),
            country: $('#country').val(),
            identification: $('#identification').val(),
            requtest: $('#request').val(),
            date_of_birth: $('#date_of_birth').val(),
            first: $('#first').val(),
            middle: $('#middle').val(),
            last: $('#last').val(),
            street1: $('#street1').val(),
            street2: $('#street2').val(),
            city: $('#city').val(),
            state: $('#state').val(),
            postal_code: $('postal_code').val(),
            country_code: $('#country_code').val()
          }),

并使用函数对数据进行字符串化而无结果

function ConvertFormToJSON(form) {
    var elems = [].slice.call(form.elements);
    var o = {};
    $.each(elems, function() {
        var $this = $(this), g = $this.data('group');
        if (g) {
            if ( !o.hasOwnProperty(g) ) o[g] = {};
            o[g][this.name] = this.value;
        } else {
            o[this.name] = this.value;
        }
        });

    return o;
    }
submitHandler: function(form) {
      var form = this;
      var json = ConvertFormToJSON(form.currentForm);
      console.log('Here is the json' + json);
      $.ajax({
        type:'POST',
        url:'webserviceURL',
        crossDomain:true,
        data: json,
        dataType: "json",
        success: function( data ){
          alert(data);
        },
        error: function ( xhr, errorType, exception ) {
          var errorMessage = exception || xhr.statusText;
          $('#USForm').fadeOut('fast');
          $('#formContain').html('<p>We are sorry, but the following error has occurred:<br />' + errorMessage +'</p>');
        }  
      })
      .always(function(){
        console.log("always:" + json);
      })
      .done(function (response){
        console.log("done:" + json);
      })
      .fail(function(){
       console.log("fail" + json);
      });
      return false;
  },
//rest of validation stuff

以下是fiddle

0 个答案:

没有答案