【问题标题】:adding text using ajax call from json string使用来自json字符串的ajax调用添加文本
【发布时间】:2013-05-26 18:51:33
【问题描述】:

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

谢谢!

【问题讨论】:

  • 控制台有错误吗?你也确定服务器支持jsonp
  • 是成功处理程序被触发,还是其他地方有问题?
  • 在您的 chrome 控制台中打开网络选项卡,查看您的请求是否通过或收到与 CORS 相关的错误?

标签: html ajax json dom


【解决方案1】:

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

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

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

.html()

.text()

.val()

【讨论】:

    【解决方案2】:

    您想使用端点在成功函数中返回的数据。正如您所写,元素的内容将被替换为字符串“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);
    }
    });
    

    【讨论】:

    • 非常感谢杰森。现在已经看到了光明的一面。我仍然收到一个错误,我不确定它是否与 ajax 调用或 Json 字符串有关。我在控制台中收到一条错误消息:“未捕获的语法错误:意外的令牌:它指向 Json 字符串的 url。这是否意味着 Json 字符串有问题?还是还有什么问题?我的 ajax 脚本出错了。顺便再次感谢您的帮助
    【解决方案3】:

    你可以在一行中处理 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多