如何通过URL访问html内容json对象

时间:2016-11-29 15:58:06

标签: html json url dom url-routing

例如,如果我的URL是www.someurlsomewhere.com/GetItemById?Id=5而我的响应是一个json对象数组。

  Success:  true
  Html: "<html><body>test</body></html>"
  FileName: "test.html"

如何说www.someurlsomewhere.com/GetItemById?Id=5?data=Html使其在响应中充当我的json对象的Html部分的链接。

1 个答案:

答案 0 :(得分:2)

您正在谈论查询参数或网址参数。添加多个参数的正确格式是将它们与www.someurlsomewhere.com/GetItemByID?Id=5&src=html分开。您的网址类似于:var data = { success: true, html: "<html><body>test</body></html>", filename: "test.html" } var el = document.createElement('html'); //creates a temporary dummy element to append to the page... although if you already have something on the page, you may use that container el.innerHTML = data.html; //here you're selecting the element and adding a string of HTML to it

要提取该信息,您需要解析URL参数,然后根据数据提供所需的信息。这可以在服务器端或客户端完成。查找URL参数解析,以获得有关如何使用您选择的语言进行操作的想法。 JavaScript中出现的一个示例是How can I get query string values in JavaScript?

在您解析了所需的URL参数后,现在需要将其呈现给页面。查找解析HTML。我将假设您在javascript中执行此操作,只是为了给您一个解析示例:

<script>
    //Assuming your URL looks like this:
    // www.someurlsomewhere.com/GetItemByID?Id=5&src=html
    function getParameterByName(name, url) {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
    }

    var src = getParameterByName('src'); //Use your parameter function to retrieve the src parameter from the URL. Currently src = 'html'

    //This is a representation of your JSON payload that you're receiving from somewhere
    var data = {
        success: true,
        html: "<html><body>test</body></html>",
        filename: "test.html"
    }

    var el = document.createElement('html'); //creates a temporary dummy element to append to the page... although if you already have something on the page, you may use that container
    el.innerHTML = data[src]; //here you're selecting the element and adding a string of HTML to it. This would translate to data.html
</script>

关于你所问的问题有很多未知数。但这是一个潜在的客户端解决方案,它检索URL参数,然后将其作为HTML传递给DOM。

{{1}}