如何使用Freshdesk API使用javascript

时间:2017-06-26 19:24:29

标签: javascript angularjs freshdesk

我有一个功能,当用户点击"提交"在表格上。除 custom_fields 外,所有内容都会提交给freshdesk。

我使用Angular 1.4和控制器,所以ctrl是我的控制器。这是我的代码:

   function postTicket() {
  var formdata = new FormData();

  var customFields = {
    "serial_number": ctrl.newTicket.serialnumber
  };
  customFields = JSON.stringify(customFields);


  formdata.append('description', ctrl.newTicket.description);
  formdata.append('subject', ctrl.newTicket.subject);
  formdata.append('type', ctrl.newTicket.type);
  formdata.append('email', ctrl.newTicket.email);
  formdata.append('custom_fields', customFields);
  formdata.append('status', 2); // open
  formdata.append('priority', 1); // low

  supportResource.postTicket(formdata).then(
    results => {
      console.log('it worked! ', results);
      ctrl.formSent = true;
    },
    error => {
      console.log('something went wrong. ', error);
    });
}

这里是supportResource代码:

function postTicket(ticket) {
  return $q(function(fulfill, reject) {
    $http({
      url: `https://${MYACCOUNT}.freshdesk.com/api/v2/tickets`,
      method: 'POST',
      headers: {
        'Authorization': 'Basic ' + btoa(MYKEY),
        'Content-Type': undefined
      },
      data: ticket
    }).then(
      results => {
        fulfill(results.data);
      },
      error => reject(error));
  });
}

我收到以下错误:"值集的类型为String.It应该是一个/一个键/值对" enter image description here

我从这里跟随了这个例子: https://github.com/freshdesk/fresh-samples/blob/master/jquery/create_ticket_with_attachment.html

我也看到了这一点:https://support.freshdesk.com/support/solutions/articles/216548-create-and-update-tickets-with-custom-fields-using-api

但是此示例使用的是CURL,我不确定如何使用FormData()发送数据http://developer.mozilla.org/en-US/docs/Web/API/FormData

1 个答案:

答案 0 :(得分:0)

我想在这里分享解决方案以防其他人遇到此问题。这特定于freshdesk API以及它对数据的期望。表单数据的语法非常简单:

  

语法

     

此方法有两个版本:两个和三个参数版本:

     
      
  • formData.append(name,value);
  •   
  • formData.append(name,value,filename);
  •   

因此,通过更改字符串中的名称以将custom_field名称引用为关联数组,如下所示:custom_fields[serial_number]然后API了解正在使用的键,并且能够读取表单数据

function postTicket() {
  var formdata = new FormData();

  formdata.append('description', ctrl.newTicket.description);
  formdata.append('subject', ctrl.newTicket.subject);
  formdata.append('type', ctrl.newTicket.type);
  formdata.append('email', ctrl.newTicket.email);
  formdata.append('custom_fields[serial_number]', ctrl.newTicket.serialnumber);
  formdata.append('status', 2); // open
  formdata.append('priority', 1); // low

  supportResource.postTicket(formdata).then(
    results => {
      console.log('it worked! ', results);
      ctrl.formSent = true;
    },
    error => {
      console.log('something went wrong. ', error);
    });
}