Hi I have to write Rest API call which will serve cross domain request
I have checked with Mozilla (rest client) with request and it serves me data now how to write via jquery/javascript in html.
{"POST to adengine":{"method":"POST","url":"http://xxx.com/Advertisement/1.0/GetAds","body":"aid=Apposaurus_xxx","overrideMimeType":false,"headers":[["Content-Type","application/x-www-form-urlencoded"]]}}
Here is my sample code in html
<html>
<title></title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
url: "http://xxx.com/Advertisement/1.0/GetAds",
type: "POST",
data: "aid=Apposaurus_xxx",
overrideMimeType:'false',
crossDomain: 'true',
dataType: 'jsonp',
headers:{"Content-Type":'application/x-www-form-urlencoded'},
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
};
</script>
</head>
<body>
<div id="resultDivContainer"></div>
<button type="button" onclick="JSONTest();">JSON</button>
</body>
</html>
Where i am wrong?
Cross Domain Request should be accomplished using JSONP. JSONP stands for JSON with Padding. I’ll try to explain it here a little.
How do you want to fetch data (script when we talk about JSON) from server? You have two ways:
XMLHttpRequestobject, and which is limited to be sent only to the same domain,<script>tag somewhere in the HTML document, mostly in the head section.The second technique is not limited to Cross-Domain Policy. However, let’s examine how browser works as our agent in these two scenarios:
ajax scenario: developer code => browser => request => server => response => browser => developer code. This means that when you use ajax, browser on behalf of you creates an HTTP Request (with
X-Requested-With: XMLHttpRequestheader field) and sends it to the server, then it gets the response base, *but it gives you the response back, so that as the developer, you have the opportunity to analyse response and do whatever you want to do with it.HTTP Get scenario: developer code => script tag in head => browser => request => server => response => browser => response execution.
See? When you use JSONP, or when you insert in simple
<script>tag in head, browser gets the script back from the server, but it runs script and that’s the end. You haven’t been hooked into the response, and you don’t have control over it. Thus, you need to provide acallbackfunction for it.callback({})differs from{}in point that when it gets executed, it gives you the opportunity to get the result and do something with it.