您可以获取一个外部文件并使用 ajax 将其解析为字符串。jQuery 方式更简洁,但原生 JS 版本可能看起来像这样:
var mdFile = new XMLHttpRequest();
mdFile.open("GET", "http://mypath/myFile.md", true);
mdFile.onreadystatechange = function(){
// Makes sure the document exists and is ready to parse.
if (mdFile.readyState === 4 && mdFile.status === 200)
{
var mdText = mdFile.responseText;
var converter = new showdown.Converter();
converter.makeHtml(mdText);
//Do whatever you want to do with the HTML text
}
}
jQuery方法:
$.ajax({
url: "info.md",
context: document.body,
success: function(mdText){
//where text will be the text returned by the ajax call
var converter = new showdown.Converter();
var htmlText = converter.makeHtml(mdText);
$(".outputDiv").append(htmlText); //append this to a div with class outputDiv
}
});
注意:这假设您要解析的文件在您自己的服务器上。如果文件在客户端(IE 用户文件),您需要采取不同的方法
更新
如果您想要的文件与您在同一台服务器上,上述方法将起作用。如果不是,那么如果您控制远程服务器,则必须研究 CORS,如果不控制,则必须研究服务器端解决方案。 这个问题提供了有关跨域请求的一些相关背景。