使用JSON将表单电子邮件发送到REST服务

时间:2013-10-07 14:17:34

标签: javascript jquery json rest

如何使用JSON将表单电子邮件发送到REST服务

我正在这样做:

// Send Mail
$('#btn_send').click(function() {

    //  Data object contact
    this.name = $('#inputnome').val();
    this.email = $('#inputemail').val();
    this.subject = $('#inputassunto').val();
    this.message = $('#textareamsg').val();
    this.toJsonString = function() {
        return JSON.stringify(this);
    };

    $.ajax({
        type: "POST",
        url: "http://localhost:8080/MailWS",
        data: contact.toJsonString(),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, status, jqXHR) {
            alert(status.toString());
        },
        error: function(jqXHR, status) {
            alert(status.toString());
        }
    });
});

1 个答案:

答案 0 :(得分:0)

我认为问题在于你没有将onclick动作绑定到按钮上。尝试将整个javascript包含在$( document ).ready(function() {});中,或者做一些更清洁的事情。

$( document ).ready(function() {
  $('#btn_send').click(function() {
    sendEmail();//
  });
});

function sendEmail(){

  var valuesArr = new Array();
  valuesArr.push($('#inputnome').val());
  valuesArr.push($('#inputemail').val());
  valuesArr.push($('#inputassunto').val());
  valuesArr.push($('#textareamsg').val());

  var jsonText = JSON.stringify(valuesArr);
  $.ajax({
      type: "POST",
      url: "http://localhost:8080/MailWS",
      data: jsonText,
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(data, status, jqXHR) {
          alert(status.toString());
      },
      error: function(jqXHR, status) {
          alert(status.toString());
      }
  });
}