2013-05-31 115 views
0

我对ajax有点新,而且我的javascript不是破旧的,我很难搞清楚这一点。我试图通过AJAX Get方法将位于单独url上的JSON字符串的值添加到我的html代码中。使用来自json字符串的ajax调用添加文本

目前,这是我的代码:

$.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

控制台中是否有错误?你也确定服务器支持'jsonp' –

+0

是成功处理程序解雇了,还是其他地方有问题? – Jason

+0

在你的chrome控制台中打开网络标签,看看你的请求是否正在通过或获取CORS相关的错误? – PSL

回答

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); 
} 
}); 
+0

甜蜜的感谢杰森。现在正在寻找更光明的一面。我仍然收到错误,但我不确定它是否与ajax调用或Json字符串有关。我的控制台出现错误,提示:“未捕获的语法错误:意外的令牌:它指向Json字符串的url。 这是否意味着Json字符串有什么问题?我的ajax脚本仍然有问题。顺便再次感谢您的帮助 – BeDesinged

2

val()用于输入。因此,您可以在此处使用.html().text()作为div元素。

如果你的ajax调用到达成功处理程序,这应该给你预期的结果。

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

.html()

.text()

.val()

0

1000个数据可以在单行中完成。

使用这个。 保持你的JSON数据作为

{"name":"raja","age":20,"register_no":"19283KSR"} 

让您的组件ID名称,如

1.cmp_name 2.cmp_age 3.cmp_register_no

在阿贾克斯成功做到这一点

for (var index in data){ 
if ($("#cmp_"+index).length != 0) 
    $("#cmp_"+index).html(data[index]); 
} 

验证您的json请参阅JSONLint

相关问题