0

我对 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 脚本中遗漏了一些东西。但老实说,我不知道是什么。有人可以伸出援助之手吗?

谢谢!

4

3 回答 3

2

val()用于输入。所以你可以在这里使用.html()div.text()元素。

如果您的 ajax 调用到达成功处理程序,这应该会给出您想要的结果。

    $("#name").html("firstName"); // or data["firstName"] ?
    $("#avatar").html("userProfileImg"); //or data["userProfileImg"]
    $("#notNum").html("numOfNotifications"); //or data["numOfNotifications"]

.html()

。文本()

.val()

于 2013-05-31T02:47:49.043 回答
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);
}
});
于 2013-05-31T02:49:19.573 回答
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

于 2013-05-31T06:41:28.870 回答