2016-09-21 96 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