0

I want to call an asp.net web service's from a different domain with javascript.

Ex :

I have the site "www.abc.com", I want it to call the web service on "www.xyz.com" with some javascript I load from X domain.

First I add the script with this :

document.write(unescape("%3Cscript src=%27http://myscript.com/script.js%27 type=%27text/javascript%27%3E%3C/script%3E"));

This is the script.js file :

$.ajax({
  type: "POST",
  url: "http://www.xyz.com/Service1.asmx/InsertIt",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: OnSuccess,
  error: function (response) {
      alert(response);
  }
});

function OnSuccess(response) {
  alert(response.d);
}

I know Cross-domain calls from within client-side code are a no-no in all major browsers. To achieve that, I think you can use CORS.

Use CORS, ie. set Access-Control-Allow-Origin header to http://your-caller-domain.com in the web

In this example, I know the caller domain : www.abc.com. but in the real life, I will never know the caller domain. I know there's other way to do a Cross-Domain call, ex : JSONP. But this technique is really complexe (for me).

So I am asking is there's an easy way to achieve a Cross-Domain call ?

1
  • You've already mention JSONP. AFAIK, using JSONP in JQuery is very similar with the code you provide (see learn.jquery.com/ajax/working-with-jsonp). Commented Feb 25, 2014 at 2:36

2 Answers 2

1

The best and safest method is using your server side framework to do your http requests which you can then present to your JS. This negates any cross browser annoyances that client side calls inherit.

Eg:

  • AJAX hits www.abc.com/getdata.ashx.
  • Execute your request to www.xyz.com using below method.
  • Return a json string or plain text. It's up to you.

WebRequest for .NET. There is an example at the bottom. Also look at HTTP handlers (.ashx) for doing requests. Not essential, but it's good to learn.

Sign up to request clarification or add additional context in comments.

Comments

0

Check the documentation bellow, u'll be able to perform cross-domain requests

http://api.jquery.com/jquery.getjson/

   $.getJSON( "http://www.xyz.com/Service1.asmx/InsertIt", function( data ) {
    alert(data.d);
   });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.