简体   繁体   English

如何从Json结果中获取值

[英]How to get a value from Json result

This is the json result I get from my controller 这是我从控制器获得的json结果

{"data":"Sunday"}

The data can say any day of the week (Sunday, Monday, etc...) 数据可以说一周中的任何一天(周日,周一等)......

On success I want to do this in ajax call 成功之后,我想在ajax调用中执行此操作

success: function(Response){
        var myresponse = Response.data;
        alert(myresponse);
}

However, it gives me undefined. 但是,它给了我未定义的。

If you are sure that you are getting a JSON response from the server, you can make use of the Ext.JSON class to decode the JSON. 如果您确定从服务器获得JSON响应,则可以使用Ext.JSON类来解码JSON。

You can use the decode() method to convert a string to an object. 您可以使用decode()方法将字符串转换为对象。 Then you should be able to easily access it. 然后你应该能够轻松访问它。

Example: 例:

var jsonObject = Ext.JSON.decode(Response.responseText);
var myData = jsonObjet.data; 

如果您使用jQuery加载此字符串,您可以使用$ .getJSON ,它将自动解析字符串并将对象作为返回值传递给“success”函数。

try to use a 试着用一个

console.log(Response);

to check the content of Response 检查响应的内容

It might be considering your response to be a string. 它可能会考虑你的回应是一个字符串。 I would do something like this: 我会做这样的事情:

success: function(Response){
        alert(typeof Response);
        var myresponse = Response.data;
        alert(myresponse);
}

If it tells you that Response is string, you need to make sure that your framework knows you are getting back JSON. 如果它告诉您Response是字符串,则需要确保您的框架知道您正在返回JSON。 For instance with jquery it might be $.getJSON(). 例如,使用jquery,它可能是$ .getJSON()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM