可以有一个自包含的JS / HTML(jQuery)文件,它在本地模拟一个AJAX调用吗?

我想创建一个发布的示例,它可以是一个自包含的HTML文件,可以在本地模拟一个AJAX调用(也就是说,如果该文件位于本地PC文件系统上,它将在您的浏览器中作为file:///path/to/file.htm打开file:///path/to/file.htm )。

我已经到达以下示例,该示例不起作用。 我想要做的就是点击“获取数据!” 按钮,使用查询字符串参数shdat向同一页面发起请求; 然后在JS中,如果页面检测到查询字符串shdat ,它应该停止进一步加载页面,并将当前文档替换为字符串(我们“发送”的数据),以便“提问者”将此作为AJAX调用的响应(最终在div数据dataholder显示)。

这是我的例子:

     .my_btn { background-color:yellow; } .dispnone { display:none }    var thishref = window.location.href.slice(0, window.location.href.indexOf('?')+1); var qstr = window.location.href.slice(window.location.href.indexOf('?')+1); console.log("qstr", qstr); if (qstr == "shdat") { // interrupt normal page loading: window.stop(); // replace entire page so far with our "data", // which will effectively "send it back" to "asker"? // (doesn't work) $(document).html("Sending some message"); } function OnGetdata(inbtn) { console.log("OnGetdata"); // http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url $.ajax(thishref + "?shdat", { success: function(data) { console.log("data ", data); }, error: function(xhr, ajaxOptions, thrownError) { console.log("error " + thishref + " : " + xhr.status + " / " + thrownError); } }); } ondocready = function() { $("#getdata").click(function(){ OnGetdata(this); }); } $(document).ready(ondocready);    

Hello World!

Here is the test:

问题是,这里的Ajax调用将完成,但是console.log("data ", data); 将显示一个XMLDocument ,它基本上是整个页面 – 而不是仅数据。

这样的事情可能会发生,如果是这样,怎么样?

好吧,我正在考虑这个问题,我想,问题是当调用file:/// ,根本就没有任何东西可以解释数据 – 就像在Unix上做cat somefile.txt一样; 你只是得到原始内容, cat本身不能做任何处理。

因此,当Ajax调用运行时,它只是将整个文件作为文本字符串读取,而不是由任何东西(包括浏览器)解释,因此我在那里的JS开关基本上不会运行。

一个快速的解决方法是使用PHP; PHP中有切换部分(对查询字符串的存在作出反应)(特别是在Ubuntu / Debian上调用的php-cli ,可能有服务器function开关-S ,但不是完整的PHP安装) ; 那么,如果你的文件在~/Desktop/tmp.php ,那么就可以简单地运行了

 php -S localhost:8080 

…在同一个文件夹( ~/Desktop )中,然后在浏览器中访问: http://localhost:8080/tmp.txt 。 这是OP文件应该如何更改,因此它在PHP下按预期工作 – 我们现在可以将其tmp.phptmp.php

          

Hello World!

Here is the test:

现在,当我点击“获取数据!” 按钮,我在JavaScript控制台中收到“数据发送一些消息”,这是我想让OP做的…