2016-07-10 233 views
0

请参阅下面的代码从我的MVC视图:AJAX返回undefined

<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script> 
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script> 

    <script type="text/javascript"> 
     function GetMessage() { 
      $.ajax({ 
       type: "GET", 
       url: "http://localhost/webapi/api/Values/", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: OnSuccess(), 
       async: false, 
       failure: function (response) { 
        alert('there was an error creating the disposal decision records') 
       } 
      }); 

      function OnSuccess() { 
       return function (response) { 
        alert(response.d); 
       } 
      } 
     } 
     GetMessage(); 
    </script> 

,并从代码:http://localhost/webapi/api/Values/

public Person Get() 
     { 
      Person p = new Person(); 
      p.id = 1; 
      p.name = "Bert"; 
      p.age = 31 
      return p; 
     } 

在成功的事件处理程序;提示未定义。为什么?

+0

什么是'response.d'? – Nic

+1

@Nic,请参阅:http://stackoverflow.com/questions/4215386/jquery-ajax-json-response-returns-key-d – w0051977

+0

尝试'console.log(response)'并查看它包含的内容。警报对调试不太好。 – JJJ

回答

-1

试试这个:

var OnSuccess = function(response) { 
     alert(response.d); 
    } 

,并在你的Ajax调用:

success: OnSuccess, 
0

每当你用的WebAPI或任何其他网络服务时,必须测试它在浏览器中你做到这一点之前, jquery-ajax

首先,您需要在浏览器中尝试http://localhost/webapi/api/Values/(确保您的服务器端正常,因为它不需要您的jQuery ajax代码)。可能你不会得到期望的结果。


现在,在任何情况下,你需要一些修复您的Ajax请求,请做以下

<script type="text/javascript"> 
    var OnSuccess = function(data) 
    { 
     alert("this is success"); // just check if this works 
     alert(data); // just check if this works 
     if(data && data.d) 
      alert(data.d); 
    } 

    function GetMessage() { 
     $.ajax({ 
      type: "GET", 
      url: "http://localhost/webapi/api/Values/", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: OnSuccess, 
      async: false, 
      error:function(er){ 
       alert(er.responseText); 
      }     
     }); 

     function OnSuccess() { 
      return function (response) { 
       alert(response.d); 
      } 
     } 
    } 
    GetMessage(); 
</script> 

如果http://localhost/webapi/api/Values/作品在浏览器中你再AJAX还必须做上述修正后的罚款。但如果没有,那么你需要看看下面

看来你的服务器端还不行。你的服务器端控制器必须有这样的代码

[RoutePrefix("api/Values")] 
public class PersonssController : ApiController 
{ 
    // GET api/Values 
    [Route("")] 
    public Person Get() { 
    { 
     Person p = new Person(); 
     p.id = 1; 
     p.name = "Bert"; 
     p.age = 31 
     return p; 
    }  
} 

后您的WebAPI控制器上面的修改,现在你应该能够找到http://localhost/webapi/api/Values/在浏览器工作正常,并且你也改变了你的jQuery的要求,因为我告诉顶部,所以一切都会好的