上篇文章介绍了Toolkit API,是一种js的前台写法
同步调用格式:
sforce.connection.method("argument1","argument2",...);
异步调用格式:
sforce.connection.method("argument1","argument2",...,"callback_function");
此次介绍的内容仍为JS前台的写法,不过是和controller交互的,他不同与action对应的method,而是一种在js代码中调用的controller 方法;
结构如下:
- Use this to specify whether or not to escape the Apex method’s response. The default value is {escape: true}.
callbackFunction接收方法调用的状态和结果作为参数。
global with sharing class AccountRemoter {
public String accountName { get; set; }
public static Account cc{ get; set; }
public AccountRemoter() { } // empty constructor
@RemoteAction
public static Account getAccount(String accountName) {
cc = [SELECT Id, name,NumberOfEmployees FROM Account WHERE Name = :accountName];
return cc;
}
}
<apex:page controller="AccountRemoter">
<script type="text/javascript">
function getRemoteAccount() {
var accountName = document.getElementById('acctSearch').value;
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.AccountRemoter.getAccount}',
accountName,
function(result, event){
if (event.status) {
//alert(result);
//console.log(result);
console.log(event);
// Get DOM IDs for HTML and Visualforce elements like this
document.getElementById('remoteAcctId').innerHTML = result.Id
document.getElementById("{!$Component.block.blockSection.secondItem.acctNumEmployees}")
.innerHTML = result.NumberOfEmployees;
} else if (event.type === 'exception') {
document.getElementById("responseErrors").innerHTML =
event.message + "<br/>\n<pre>" + event.where + "</pre>";
} else {
document.getElementById("responseErrors").innerHTML = event.message;
}
},
{escape: true}
);
}
</script>
<input id="acctSearch" type="text"/>
<button οnclick="getRemoteAccount()">Get Account</button>
<div id="responseErrors"></div>
<apex:pageBlock id="block">
<apex:pageBlockSection id="blockSection" columns="2">
<apex:pageBlockSectionItem id="firstItem">
<span id="remoteAcctId"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="secondItem">
<apex:outputText id="acctNumEmployees"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>