2016-09-21 57 views
0

我拿了两个项目。一个用于apis,另一个用于显示apiresult。没有得到API返回值

这是我的API控制器:

public class HomeController : ApiController 
    { 
     [HttpGet] 
     public string Index() 
     { 
      return "Hello world"; 
     } 
    } 

,这是我的显示控制器:

 public ActionResult Index() 
     { 
      return View(); 
     } 

和指数控制器的观点是波纹管:

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<input type="submit" value="Get Value" id="btnSubmit" onclick="GetData();" /> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> 
<script type="text/javascript"> 
    function GetData() { 
     var uri = 'http://localhost:50951/api/Home'; 
     $.ajax({ 
      url:uri, 
      type: "Get", 
      dataType: "JSON", 
      success: function (data) { 
       alert(data); 
      }, 
      error: function (xhr, status, error) { 
       alert("error"); 
      } 
     }); 
    } 
</script> 

当我点击它调用api的GetData按钮,并且api返回字符串值。但在JavaScript中,我没有得到API返回值。

+0

你的API解决方案和MVC解决方案是分开的项目吗? –

+0

您的浏览器控制台中是否有任何错误? – Curt

回答

0

要么根本:

1)编辑Index()方法:

[HttpGet] 
public JsonResult Index() 
{ 
    return Json("Hello world", JsonRequestBehavior.AllowGet); 
} 

2)从jQuery AJAX调用取出dataType: "JSON"

+0

我尝试删除dataType:“JSON”,但我仍然没有得到api返回值 – sadasiva

+0

如果使用Chrome或Firefox浏览到“http:// localhost:50951/api/Home”,会发生什么情况? – Frits

+0

Hello World sadasiva