如何使用ajax调用web api方法 [英] How do I call a web api method using ajax

查看:225
本文介绍了如何使用ajax调用web api方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:



$ .ajax({

类型:'GET',

url:'http:// localhost:51914 / PlayerPortal / User / Test',

})。done(function(data){

self.user( data.userName);

//在会话存储中缓存访问令牌。

sessionStorage.setItem(tokenKey,data.access_token);

})。失败(showError);



当我按CTRL +点击上面的网址时,通话工作正常。

但是当我跑它通过网页,我得到

状态:0

statusText:错误



如何调试这个?可能有什么不对。

对不起,我对此很新。



我尝试了什么:



我尽我所能。



我可以创建一个结合MVC 5的Web API 2在一个解决方案中,但我想为每个解决方案单独解决。我来自WPF / WCF背景。



我想要一个独立的Web API 2解决方案,并从独立的MVC 5解决方案中调用它。

简单,对吧?

I have the following code:

$.ajax({
type: 'GET',
url: 'http://localhost:51914/PlayerPortal/User/Test',
}).done(function (data) {
self.user(data.userName);
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
}).fail(showError);

When I CTRL+click on the url above, the call works.
But when I run it through the webpage, I get
status: 0
statusText: error

How do I debug this? What could be wrong.
Sorry, I am very new to this.

What I have tried:

I have tried everything I can.

I can create a Web API 2 combined with MVC 5 in one solution, but I want separate solutions for each. I come from a WPF/WCF background.

I want a standalone Web API 2 solution and call it from a standalone MVC 5 solution.
Simple, right?

推荐答案

.ajax({

类型:'GET',

url: 'http:// localhost:51914 / PlayerPortal / User / Test',

})。done(function(data){

self.user(data.userName) ;

//在会话存储中缓存访问令牌。

sessionStorage.setItem(tokenKey,data.access_token);

})。失败(showError);



当我按CTRL +点击上面的网址时,通话工作正常。

但是当我通过网页运行时,我得到

状态:0

statusText:错误



如何调试?可能有什么不对。

对不起,我对此很新。



我尝试了什么:



我尽我所能。



我可以创建一个结合MVC 5的Web API 2在一个解决方案中,但我想为每个解决方案单独解决。我来自WPF / WCF背景。



我想要一个独立的Web API 2解决方案,并从独立的MVC 5解决方案中调用它。

简单,对吧?
.ajax({
type: 'GET',
url: 'http://localhost:51914/PlayerPortal/User/Test',
}).done(function (data) {
self.user(data.userName);
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
}).fail(showError);

When I CTRL+click on the url above, the call works.
But when I run it through the webpage, I get
status: 0
statusText: error

How do I debug this? What could be wrong.
Sorry, I am very new to this.

What I have tried:

I have tried everything I can.

I can create a Web API 2 combined with MVC 5 in one solution, but I want separate solutions for each. I come from a WPF/WCF background.

I want a standalone Web API 2 solution and call it from a standalone MVC 5 solution.
Simple, right?


这是由于CORS:Origin由1)主机,2)端口和3)协议定义

我猜我我会在一个应用程序中完成所有操作,就像我在其他地方看到的那样。
It IS due to CORS: Origin is defined by 1) host, 2) port, and 3) protocol
I guess I'll make it all in one app, like I've seen everywhere else.


这篇关于如何使用ajax调用web api方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆