【问题标题】:How to access an html content json object via URL [closed]如何通过 URL 访问 html 内容 json 对象 [关闭]
【发布时间】:2016-11-29 15:58:05
【问题描述】:

例如,如果我的 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 部分的链接一样。

【问题讨论】:

    标签: html json url dom url-routing


    【解决方案1】:

    您在谈论查询参数或 URL 参数。添加多个参数的正确格式是用&amp; 分隔它们。您的 URL 类似于:www.someurlsomewhere.com/GetItemByID?Id=5&amp;src=html

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

    解析出所需的 URL 参数后,现在需要将其呈现到页面。查找解析 HTML。我假设你是用 javascript 做的,只是给你一个解析的例子:

    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 参数,然后将其作为 HTML 传递给 DOM。

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

    【讨论】:

    • 当我尝试 www.someurlsomewhere.com/GetItemByID?Id=5&data=html 时,我得到的页面类似于 www.someurlsomewhere.com/GetItemByID?Id=5
    • 好吧,这又回到了我的说法,这里有很多未知数。根据您收到的 JSON 有效负载,您需要将其呈现到页面。如果你没有做任何事情来解析 HTML(服务器端或客户端),那么它看起来不会有什么不同。
    猜你喜欢
    • 2015-05-12
    • 1970-01-01
    • 2022-09-29
    • 2017-04-15
    • 2011-01-16
    • 2017-02-24
    • 1970-01-01
    • 2011-03-26
    • 2012-02-28
    相关资源
    最近更新 更多