从项目之外的一个普通的HTML文件调用MVC4的Web API [英] Calling MVC4 Web API from a Normal HTML File outside the project
问题描述
我一直努力学习MVC4的Web API。我从VS2010本身运行我的项目。
我的项目URL为localhost:31735
当直接调用浏览器从自身的WebAPI。它的工作原理本地主机一样:31735 / API /产品/
我现在想从项目之外的一个普通的HTML文件调用的WebAPI。
我试图做到这一点。
$(文件)。就绪(函数(){
//发送一个AJAX请求
$ .getJSON(HTTP://本地主机:31735 / API /产品/
功能(数据){
//如果成功,数据包含的产品列表。
$。每个(数据,功能(键,VAL){ //格式化文本显示。
无功海峡= val.Name +':$'+ val.Price; //为产品添加列表项。
$('<李/>',{HTML:STR})。appendTo($('#产品'));
});
});
});
但这个亘古不变的工作。你能有所帮助。
我现在想从项目之外的一个普通的HTML文件调用的WebAPI。
块引用>您不能这样做,因为同源策略限制其prevents的您发送跨域AJAX请求。有不同的可能的解决方法中,其中一成由使用< A HREF =http://en.wikipedia.org/wiki/JSONP相对=nofollow的> JSONP而不是JSON。
下面的一个帖子介绍如何实现通过使用自定义介质格式。
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.
解决方案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.
这篇关于从项目之外的一个普通的HTML文件调用MVC4的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!