在Salesforce中使用Javascript调用Apex方法 - Salesforce RemoteAction and webService

场景说明】:很多时候,我们会经常遇到这样的难题,对于一个按钮既想让他调用js方法,又想调用apex方法来解决某些需求,这时候需要使用到RemoteAction或者webService了。

JS Remoting基础知识】:

In Salesforce,we can make asynchronous requests from Visualforce Page,via RemoteAction or webService.
I will share you the usage of RemoteAction and webService In this post.

The Difference

1. Using webService, can call not only the Page Controllers but also other Classes, which can be Common Classes.
2. Using webService, will cost API request,and RemoteAction will not.
3. Using webService, the methods of Class must be global.

RemoteAction

Using RemoteAction(JavaScript Remoting) allows us to call methods in Apex controllers and get a callback with return data from JavaScript. 
The @RemoteAction methods in Apex must be static and either global or public.
The following is the sample code for RemoteAction.

RemoteActionDemo.page

<apex:page controller="RemoteActionDemoCls">
  <script type="text/javascript">
  function callRemoteAction(){
      var rId = '00110000010MIxE';
      Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.RemoteActionDemoCls.getAccount}',
        rId,
        function(result, event){
            if(event.status){
                var account = result;
                console.log('Response is : ' + JSON.stringify(account));
                console.log('Account Name is : ' + account.Name);
                console.log('Account Owner Name is : ' + account.Owner.Name);
            } else {
                alert(event.message);
            }
        },
        {escape: true}
    );
    //Also can use the below way if you don't warry about NameSpace
    /* 
      RemoteActionDemoCls.getAccount(
    		rId,
        function(result, event){
          //do something...
        },
        {escape: true}
    	);
     */
  }
  </script>
  <apex:pageblock title="A RemoteAction Demo Page" >
      <input type="button" onclick="callRemoteAction();" value="Call RemoteAction" />
  </apex:pageblock>
</apex:page>

RemoteActionDemoCls.cls

public with sharing class RemoteActionDemoCls{
    // Get Account by Id
    @RemoteAction
    public static SObject getAccount(String sfdcId) {
        return [SELECT Id, Name, OwnerId, Owner.Name FROM Account WHERE Id = :sfdcId LIMIT 1];
    }
}

Response

 Response is : {"Id":"00110000010MIxEAAW","Name":"Test Account","OwnerId":"00510000002y8I6AAI","Owner":{"Name":"xgeek","Id":"00510000002y8I6AAI"}}
 Account Name is : Test Account
 Account Owner Name is : xgeek

view rawresponse.log hosted with  by GitHub

webService

Using webService(Apex in AJAX) need to include the following lines in your AJAX code

 <apex:includeScriptvalue="/soap/ajax/25.0/connection.js"/>
 <apex:includeScriptvalue="/soap/ajax/25.0/apex.js"/>

view rawsoap ajax.html hosted with  by GitHub

The webService methods in Apex must be static and Class must be global. Here is the sample code for webService.

WebServiceDemo.page

<apex:page>
  <apex:includeScript value="/soap/ajax/25.0/connection.js"/>
  <apex:includeScript value="/soap/ajax/25.0/apex.js"/>
  <script type="text/javascript">
  function callWebService(){
      var rId = '00110000010MIxE';
      sforce.connection.sessionId = '{!$Api.Session_ID}';
      var results = sforce.apex.execute("WebServiceDemoCls","getAccount",{sfdcId:rId});
      var account = results[0];
      console.log('Response is : ' + JSON.stringify(results));
      console.log('Account Name is : ' + account.Name);
      console.log('Account Owner Name is : ' + account.Owner.Name);
  }
  </script>
  <apex:pageblock title="A WebService Demo Page" >
      <input type="button" onclick="callWebService();" value="Call WebService" />
  </apex:pageblock>
</apex:page>

WebServiceDemoCls.cls

global with sharing class WebServiceDemoCls{
    // Get Account by Id
    webService static SObject getAccount(String sfdcId){
        Account account = [SELECT Id, Name, OwnerId, Owner.Name FROM Account WHERE Id = :sfdcId LIMIT 1];
        return account;
    }
}

Response

 Response is : [{"Id":"00110000010MIxEAAW","Name":"Test Account","Owner":{"Id":"00510000002y8I6AAI","Name":"xgeek"},"OwnerId":"00510000002y8I6AAI"}]
 Account Name is : Test Account
 Account Owner Name is : xgeek

view rawResponse.log hosted with  by GitHub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值