在返回的JSON数据上创建href [英] Creating an href on Returned JSON Data

查看:262
本文介绍了在返回的JSON数据上创建href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些从填充表格的ajax请求返回的基本JSON数据

I have some basic JSON data returned from an ajax request which populates a table

JSON

  {"data": {
      "id": "100",
      "name": "file name",
      "url": "www.somesite.com/abc/xyz",
       //etc...
   }  }

ID   | 100
name | file name
url  | www.somesite.com/abc/xyz

我想使用url值作为href创建动态锚标记-我知道一旦返回数据就可以在回调函数中完成此操作,但是我想知道是否有一个更简单的(或最简单的方法)来完成此任务

I'd like to create a dynamic anchor tag with the url value as the href - I know this can be done within a callback function once the data is returned, but I'm wondering if there is a simpler (or the simplest) method to accomplish this

所需的表输出

ID   | 100
name | file name
url  | Click Here! //obviously the link to mysite.com/abc/xyz

推荐答案

每个AJAX请求都是异步的,因此除了在回调(传统方法或使用Promise封装)中处理它之外,别无其他选择.

Every single AJAX request is asynchronous, so there is no other option but to handle it in a callback (traditional or wrapped in promise).

这就是我要做的:

// Get data is some function that makes the request and accepts a callback...
getData(function(data){
    // Build an anchor tag...
    var link = document.createElement('a');
    link.setAttribute('href', data.url);
    link.innerHTML = 'Click Here!';

    // Add it to the element on the page.
    var table = document.getElementById("table");
    table.appendChild(aTag);
});

请确保您修改了代码以将其添加到页面,根据您的标记,代码将有所不同.

Make sure you modify the code to add it to the page, it will be different based on your markup.

灵感来自:如何添加锚点在Javascript中动态标记到div?

这篇关于在返回的JSON数据上创建href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆