1

I have trying to learn MVC4 Web API. I am running my project from VS2010 itself.

My project URL is localhost:31735

When directly calling the WebAPI from browser itself. It works like localhost:31735/api/products/

I now want to invoke the Webapi from a normal HTML file outside the project.

I tried to do this

 $(document).ready(function () {
           // Send an AJAX request 
            $.getJSON("http://localhost:31735/api/products/",
            function (data) {
            // On success, 'data' contains a list of products. 
               $.each(data, function (key, val) {

                // Format the text to display. 
                var str = val.Name + ': $' + val.Price;

                // Add a list item for the product. 
                $('<li/>', { html: str }).appendTo($('#products'));
            });
        });
    });

But this doesnot work. Can you help.

1 Answers1

3

I now want to invoke the Webapi from a normal HTML file outside the project.

You can't do this because of the same origin policy restriction which prevents you from sending cross domain AJAX requests. There are different possible workarounds, one of which consists into using JSONP instead of JSON.

Here's a post which describes how to achieve that by using a custom media formatter.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928