W3C 验证器通过 ajax 在本地主机上离线

问题描述 投票:0回答:1

我习惯于对 Brackets 文本编辑器进行编程,并且我已经安装了 W3C 验证器,但它在我在线时可以工作,但在离线时却不能。我尝试安装 https://validator.w3.org/docs/install.html 并运行到 localhost:8888 但括号的扩展仅通过 ajax (javascript) 连接。是否可以将 ajax 发送到原始 W3C 网站?

javascript w3c w3c-validation adobe-brackets
1个回答
1
投票

这里是 W3C HTML 检查器(验证器)的维护者。是的,可以向当前检查器的本地实例发送 ajax 请求。要使用 Fetch 来执行此操作并获取 JSON 格式的结果:

var checkerUrl = "http://localhost:8888/?out=json"
fetch(document.location.href)
.then(function(currentDoc) { return currentDoc.text(); })
.then(function(htmlSource) {
    fetch(
        checkerUrl, {
        method: "POST",
        mode: "cors",
        body: htmlSource,
        headers: new Headers({ "Content-Type": "text/html;charset=utf-8" })
    })
    .then(function(checkerResponse) { return checkerResponse.json(); })
    .then(function(jsonOutput) {
        console.dir(jsonOutput.messages);
    })
});

这显示了以检查员期望的方式交付请求所需遵循的基本步骤:

  • 将文档作为 POST 正文发送给检查器(在本例中为当前文档)
  • 告诉检查器将其结果格式化为 JSON (
    out=json
    )
  • text/html;charset=utf-8
    设置为您发送给检查器的 POST 正文的媒体类型

检查器还支持

multipart/form-data
为其提供要检查的 HTML 源代码,但将源代码作为 POST 正文提供给它是首选(也是更好)的方法。

如果您想使用 JQuery

fetch()
而不是使用
$.ajax(…)
,这里有一个示例:

var checkerUrl = "http://localhost:8888/?out=json"
$.get(document.location.href,
function(htmlSource)
{
    $.ajax({
        url: checkerUrl,
        type: "POST",
        crossDomain: true,
        data: htmlSource,
        contentType: "text/html;charset=utf-8",
        dataType: "json",
        success: function (jsonOutput) {
            console.dir(jsonOutput.messages);
        }
    });
});

如果您想使用老式 XHR 而不是

fetch()
或 JQuery
$.ajax(…)
,但不清楚如何处理这种情况下的细节,请告诉我,我也可以发布一个示例。

在所有情况下,

.messages
JSON 输出都是一个对象数组,每个对象都包含以下内容:

firstColumn: 1
lastColumn: 6
lastLine: 4
message: "Unclosed element “span”."
type: "error"

检查器 JSON 格式的文档提供了检查器发出的 JSON 的更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.