我正在尝试将一些表单数据作为JSON对象发送到sample app on Force.com。我使用jQuery获取表单数据并将其POST到我的服务器上的PHP文件,然后将其发送到上面链接的示例应用程序。我从示例应用程序得到的响应然而告诉我,我一路上犯了一些错误。
与示例Force.com应用程序对话的PHP文件:
<?php
$url = 'https://cmsamp.secure.force.com/GenericApp/services/apexrest/GenericApp';
$data = $_POST[ 'data'];
$options = array('http' => array('method' => 'POST','content' => http_build_query($data)));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
?>
将表单数据发布到PHP文件的客户端jQuery代码:
var sample_form_data = {"attributes":{"type":"Generic_App__c"},"Application_Type__c":"iPay","Return_Email__c":"lsmith@cmsrep.com","Name":"Bus Test","ACHRejectFee__c":"123456789","ApplicationDate__c":"2000-01-01","BusinessPhone__c":"(555) 123-4567","Email__c":"thetest@testemail.com","InternetPercentage2__c":"0","MailingState__c":"CA","MOTO7__c":"true","NumOfLocations__c":"15"};
$.post( url, { data: JSON.stringify( sample_form_data ) }, function( result ) {
console.log( result );
});
来自Force.com应用程序的回复:
"No content to map to Object due to end of inputInsert failed.
First exception on row 0;
first error: REQUIRED_FIELD_MISSING,
Required fields are missing: [Name]: [Name]"
期望的“成功”回应:
"Success:
Generic App Object: Bus Test; was successfully created and inserted"
这是php代码中var_dump($data)
的输出(为了可读性添加了换行符:
string(405)
"{\"attributes\":
{\"type\":\"Generic_App__c\"},
\"Application_Type__c\":\"iPay\",
\"Return_Email__c\":\"lsmith@cmsrep.com\",
\"Name\":\"Bus Test\",
\"ACHRejectFee__c\":\"123456789\",
\"ApplicationDate__c\":\"2000-01-01\",
\"BusinessPhone__c\":\"(555) 123-4567\",
\"Email__c\":\"thetest@testemail.com\",
\"InternetPercentage2__c\":\"0\",
\"MailingState__c\":\"CA\",
\"MOTO7__c\":\"true\",
\"NumOfLocations__c\":\"15\"
}"
通用应用程序只希望获得具有适当字段的JSON对象。当我通过REST客户端提交以下内容时,它按预期工作(同样,为了可读性添加了换行符):
{"attributes":
{"type":"Generic_App__c"},
"Application_Type__c":"iPay",
"Return_Email__c":"test@example.org",
"Name":"Bus Test",
"ACHRejectFee__c":"123456789",
"ApplicationDate__c":"2000-01-01",
"BusinessPhone__c":"(555) 123-4567",
"Email__c":"thetest@testemail.com",
"InternetPercentage2__c":"0",
"MailingState__c":"CA",
"MOTO7__c":"true",
"NumOfLocations__c":"15"}
任何人都有关于如何解决这个问题的想法?
答案 0 :(得分:2)
从那些var_dumps的外观来看,我要说你需要在使用之前从$ data中删除这些斜杠。试试stripslashes。
答案 1 :(得分:0)
http_build_query也需要一个数组。由于您的数据已经是json字符串,我认为您应该省略它。您可能需要对其进行url编码,但您应该只使用常规的urlencode函数。
另外,我不熟悉你正在使用的php上下文机制,我对php.net文档非常不满意,但我无法摆脱这种唠叨的感觉'content' => $data
正在做的不仅仅是设置内容。您是否有实际使用'content'
选项的流上下文的良好文档链接?