我对ajax有点新鲜,我的javascript不是破旧我很难搞清楚这一点。我正在尝试通过AJAX Get方法将位于单独url上的JSON字符串中的值添加到我的html代码中。
目前这是我的代码:
$.ajax({
dataType: "jsonp",
jsonp: 'callback',
cache: false,
url: "http://www.url.com/userInfo/currentUserInfo",
success: function(data) {
$("#name").val("firstName");
$("#avatar").val("userProfileImg");
$("#notNum").val("numOfNotifications");
}
});
HTML
<div id="name"></div> <div id="avatar"></div> <div id="notNum"></div>
我很确定我在ajax脚本中遗漏了一些东西..但说实话,我无法弄清楚是什么。有人能伸出援助之手吗?
谢谢!
答案 0 :(得分:2)
val()
用于输入。因此,您可以在此处使用.html()
或.text()
作为div元素。
如果您的ajax调用达到成功处理程序,则应该提供您的预期结果。
$("#name").html("firstName"); // or data["firstName"] ?
$("#avatar").html("userProfileImg"); //or data["userProfileImg"]
$("#notNum").html("numOfNotifications"); //or data["numOfNotifications"]
答案 1 :(得分:1)
您希望使用终点在成功函数中返回的数据。正如你所写的那样,元素的内容将被字符串“firstName”,“userProfileImg”,“numOfNotifications”替换,这可能不是你的意图。
此外,您需要使用text()
函数将文本添加到div。如果您的服务返回HTML,请改用html()
函数。
$.ajax({
dataType: "jsonp",
jsonp: 'callback',
cache: false,
url: "http://www.url.com/userInfo/currentUserInfo",
success: function(data) {
// use html() if any of the data fields contain markup
$("#name").text(data.firstName); markup
$("#avatar").text(data.userProfileImg);
$("#notNum").text(data.numOfNotifications);
}
});
答案 2 :(得分:0)
1000的数据可以单行完成。
使用它。 保持你的json数据为
{"name":"raja","age":20,"register_no":"19283KSR"}
保持您的组件ID名称
1.cmp_name 2.cmp_age 3.cmp_register_no
在你的ajax成功中做到这一点
for (var index in data){
if ($("#cmp_"+index).length != 0)
$("#cmp_"+index).html(data[index]);
}
要验证您的json,请参阅JSONLint