2013-05-02 88 views
1

我有一个ASP.NET MVC Web API,我从$ .ajax()方法调用。从我的API返回正确的JSON,但该对象不可访问。尝试登录的价值为 “姓名” 当我收到的控制台的错误是:

Uncaught TypeError: Cannot read property 'Name' of undefined

JSON:

[{"id":2,"Name":"thom","Picture":"thom.jpg","About":"I'm a guy. This is my profile. Now quit staring and get out of here.","Location":"London"}] 

的jQuery:

$.ajax({ 
      cache:false, 
      type: 'GET', 
      dataType: 'json', 
      url: 'http://localhost:3235/Users/searchUsers?callback=?&searchString=' + searchString, 
      complete: function (data) { 
       console.log(data[0].Name); 
      } 
     }); 

任何帮助,将不胜感激。谢谢!

+0

尝试记录数据是什么。 – 2013-05-02 15:40:36

+0

如果你只是'console.log(data)'来查看返回的内容,而不是仅仅知道'Name'不存在,你能显示什么日志吗? – 2013-05-02 15:40:41

+0

你可能会用'content-type'的'text/html'。在JS中使用'JSON.stringify(result)'或发送正确的头文件和响应。 – 2013-05-02 15:40:52

回答

9

我想你的意思是使用success函数。 complete函数不会将data作为参数。

+2

我不敢相信我也没注意到:P – 2013-05-02 15:43:19

+0

+1。我不能相信。以为眯眼就解决了它:D – Ejaz 2013-05-02 15:44:31

+0

@Ejay:是的,我完全错过了那条船。甚至没有考虑回调类型。虽然我不知道Yatrix答案中的问题是否也会发挥作用。 – 2013-05-02 15:46:23

4

the docs

complete
Type: Function(jqXHR jqXHR, String textStatus)
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

的方法的第一个参数是所接收的数据。你可以通过jqXHR对象得到它,但我不认为你真的需要使用这个选项。使用success代替:

success
Type: Function(PlainObject data, String textStatus, jqXHR jqXHR)
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.

1

雅正在取得服务调用完成后的火灾和它不包含从服务响应数据..

使用

$.ajax({ 
url:'ur url', 
type:'GET' 
success:function(data){ 
// way to acces ur object code goes here 


console.log(data[0].Name); 


}, 
error:function(){ 
// Error handling 
} 
}); 

编码快乐