我正在使用 Jersey 和 JQuery 为客户端制作一个 Web 应用程序。 我有以下返回 JSON 字符串的 URL:
http://localhost:8080/messenger/webapi/messages/1
返回:
{"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}
当在浏览器中输入时。
现在我尝试使用以下 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);
})
});
}
});
编辑:当按下“btnRegister”时,根本不显示任何内容
这对我来说毫无意义。
最佳答案
成功回调函数中存在一些不需要的 $
包装,并且在设置 dataType:'json'
时无需解析响应。为了更好地理解$.ajax()
阅读文档 here 。
$(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);
}
});
}
});
您可以使用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']);
关于javascript - 如何使用 JQuery 中的 data 参数解析 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31690777/