如何使用Coldfusion 9将JSON发布到远程URL?

时间:2012-01-19 18:17:53

标签: jquery json coldfusion

我们正在尝试与需要JSON格式数据的远程API进行通信。我们尝试使用JQuery如下提交,但是得到了SOP错误:

<script type="text/javascript">
  $.ajax({
    username: 'username',
    password: 'password',
    url:  "https://api.e2ma.net/123/members/add",
    dataType: 'json',
    type: 'POST',
    data:
     {
       "fields": {
       "name_first": "Name"
     },
     "email": "email@domain.com"
    }
  });
</script>

不幸的是,他们的API 不支持支持 JSONP

我们如何直接从Coldfusion 9中将这个JSON数据发布到他们的远程API?

另外,我们需要做些什么才能从他们的API 解析响应

以下是文档的链接:http://myemma.com/api-docs/

以下是来自这些文档的简单添加新成员调用的片段:

import_single_member(account_id)
POST /#account_id/members/add

Adds or updates an audience member

Parameters: 

  email (string) – Email address of member to add or update
  fields (dictionary) – Names and values of user-defined fields to update
  group_ids (integer) – Optional. Add imported members to this list of groups.
  signup_form_id – Optional. Indicate that this member used a particular signup form.

Returns:    
  The member_id of the new or updated member, and whether the member was added or an  existing member was updated

Example:

POST /123/members/add
{
  "fields": {
    "first_name": "Benjamin"
  }, 
  "email": "benjamin@myemma.com"
}

{
  "added": true, 
  "member_id": 1024
}

感谢。

1 个答案:

答案 0 :(得分:1)

您需要构建代理,因为您无法从JavaScript向另一台服务器发送邮件。您的JS代码应该类似于:

$.ajax({
url:  "https://yourserver/proxy.cfm",
dataType: 'json',
type: 'POST',
data:
 "name_first": "Name",
 "email": "email@domain.com"
}
});

你的ColdFusion代码应该是这样的:

<cfhttp url="https://api.e2ma.net/123/members/add" method="post" username="username" password="password">
    <cfhttpparam name="email" value="#form.email#">
    <cfhttpparam name="fields" value='{"name_first":"#form.name_first#"}'>
</cfhhtp>

我不确定这些字段是否符合所需的格式,但ti应该非常接近。

在您发布帖子后,您还可以将这些内容返回给JavaScript:

<cfoutput>#cfhttp.filecontent#<cfoutput>