Reputation: 531
In Dynamics CRM, I have a javascript file that needs to call an external web service (cross domain). This is a pure JS file; no HTML.
JQUERY cannot be used here (Dynamics limitation) so I need to call the cross domain web service through java script alone.
Does anyone have a example of calling a cross domain web service with javascript alone?
JSONP doesn't seem to work since I can't use an HTML element inside the file.
Upvotes: 1
Views: 1347
Reputation: 79
You could try using Sys.Net.WebRequest. This library is used by MS Dynamics CRM 2016 to perform its Web API requests. It's referenced in their Microsoft.Ajax.js resource. Therefore, you don't need to reference it in your .js
Web Resource.
You can find usage examples on the the Sys.Net.WebRequest page. Here is an example of how to call a Dynamics CRM Action using this library:
var kaId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");
var wr = new Sys.Net.WebRequest();
wr.set_url(myCustomGetWebApiUrl() + "knowledgearticles(" + kaId + ")/Microsoft.Dynamics.CRM.new_MyCustomBoundAction");
wr.set_httpVerb("POST");
wr.set_body(null);
var headers = wr.get_headers();
headers["Content-Length"] = 0;
headers["Content-Type"] = "application/json";
headers["Accept"] = "application/json";
headers["OData-Version"] = "4.0";
wr.add_completed(function (executor) {
var actionResponse = JSON.parse(executor.get_responseData());
if (actionResponse)
console.log(actionResponse);
else
alert("An error occurred: " + executor.get_statusText());
});
wr.invoke();
Upvotes: 0
Reputation: 23300
You can do it in C# code: create an Action, either register a plugin to it or make the code a Code Activity, then invoke the Action from JS. See https://msdn.microsoft.com/en-us/library/mt607600.aspx for details on invoking actions from the WebAPI.
In the C# code, you're free to use i.e. WebClient
to communicate with outside world (see a sample here: https://msdn.microsoft.com/en-us/library/gg509030.aspx)
Upvotes: 1
Reputation:
I recommend you to use fetch. Fetch is a native way for your browser to request HTTP resources. However, it isn't supported on older browsers so you could use a polyfill if you want to support these browsers.
If you wanna call cross domain, you should call fetch with this option set:
fetch('http://domain.example/', { mode: 'cors' });
Upvotes: 0