[英]How can I parse JSON using the data parameter in JQuery?
I am making a web application using Jersey and JQuery for client-side. 我正在使用Jersey和JQuery在客户端创建Web应用程序。 I have the following URL that returns a JSON string:
我具有以下返回JSON字符串的URL:
http://localhost:8080/messenger/webapi/messages/1
returns: 返回:
{"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}
when typed into the browser. 在浏览器中输入时。
Now I am attempting to get this data client-side using the following JQuery functions: 现在,我尝试使用以下JQuery函数获取此数据客户端:
var rootURL = "http://localhost:8080/messenger/webapi/messages";
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL +"/1",
dataType: "json", // data type of response
success: (function(data) {
var obj = jQuery.parseJSON(data);
alert('ID: ' + obj.id);
})
});
}
}); });
EDIT: When the "btnRegister" is pressed nothing is displayed at all 编辑:当按下“ btnRegister”时,什么都不会显示
which just doesn't make sense to me. 这对我来说毫无意义。
There is some unwanted $
wrapping in success callback function, also there is no need to parse the response as you set dataType:'json'
. 成功回调函数中有一些不必要的
$
包装,也不需要在设置dataType:'json'
解析响应。 For better understanding of $.ajax()
read documentation here . 为了更好地理解
$.ajax()
阅读此处的文档。
$(function() { $('#btnRegister').click(function() { var username = $('#username').val(); addMessage(); }); function addMessage() { var url = rootURL; $.ajax({ type: 'GET', url: rootURL + "/1", dataType: "json", // data type of response success: function(data) { //----^----------- remove the $ sign alert('ID: ' + data); } }); } });
You can access the value using obj.prop
or obj['prop']
您可以使用
obj.prop
或obj['prop']
访问该值
var obj= {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}; alert(obj.author); alert(obj['author']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.