加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

用browser-sync搭建server,ajax的load()方法运行报错

发布时间:2020-12-16 03:33:30 所属栏目:百科 来源:网络整理
导读:关于使用 browser-sync 搭建 server ajax的load方法运行时报错的解决办法如下 load 的时候针对特定的 HTML 标签 去掉被 load 页面中的 body 标签 被 load 的页面只包含需要加载的内容 摘要:jQuery 中的 Ajax 及其相关的方法,均需要运行在 server 中,使用
    • 关于使用 browser-sync 搭建 server ajax的load方法运行时报错的解决办法如下
      • load 的时候针对特定的 HTML 标签
      • 去掉被 load 页面中的 body 标签
      • 被 load 的页面只包含需要加载的内容

摘要:jQuery 中的 Ajax 及其相关的方法,均需要运行在 server 中,使用 browser-sync 搭建 server 来运行 jQuery 中 load() 方法,会有报错。


关于browser-sync,请看这里:browser-sync 。


我们还是以 JQuery中的load()、$.get()和$.post()详解 这篇文章中 load() 方法的 demo 为例:
我们在 browser-sync 搭建的 server 中,用 demo1.html 页面去 load test.html 中的内容。

demo1.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jq-load</title>
</head>
<body>
  <script src="https://cdn.bootcss.com/jquery/1.7.1/jquery.min.js"></script>
  <script language="javascript" type="text/javascript"> $(function(){ $("#send").click(function(){ $("#resText").load("test-jq-load.html"); }) }) </script>
  </head>
  <body>
    <input type="button" id="send" value="Ajax获取" />
    <div class="comment">
        已有评论:
    </div>
    <div id="resText" ></div>
</body>
</html>
test.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div class="comment">
    <h6>张三:</h6>
    <p class="para">沙发.</p>
  </div>
  <div class="comment">
    <h6>李四:</h6>
    <p class="para">板凳.</p>
  </div>
  <div class="comment">
     <h6>王五:</h6>
     <p class="para">地板.</p>
  </div>
</body>
</html>

正常情况下,我们期待的结果是这样的:

但是在 browser-sync 搭建的 server 中,我们没有看到任何结果,提示错误信息如下:

关于使用 browser-sync 搭建 server ,ajax的load()方法运行时报错的解决办法如下:

1. load 的时候,针对特定的 HTML 标签

使用 load() 方法的 URL参数 来达到目的。通过为URL参数指定选择符,就可以很方便地从加载过来的 HTML 文档里筛选出所需要的内容。
load() 方法的 URL参数的语法结构为:“url selector”。注意,URL和选择器之间有一个空格。

在本例中,将 demo1.html 中的

$("#resText").load("test-jq-load.html");

修改成如下:

$("#resText").load("test-jq-load.html div");

或者

$("#resText").load("test-jq-load.html .comment");

2. 去掉被 load 页面中的 body 标签

在本例中,将 test.html 中的一对 body 标签去掉。

3. 被 load 的页面只包含需要加载的内容

在本例中,将 test.html 的内容改为:

<div class="comment">
 <h6>张三:</h6>
 <p class="para">沙发.</p>
</div>
<div class="comment">
 <h6>李四:</h6>
 <p class="para">板凳.</p>
</div>
<div class="comment">
 <h6>王五:</h6>
 <p class="para">地板.</p>
</div>

以上 3 种方法,任选其一,均可解决。

本文参考文章如下:
http://stackoverflow.com/questions/36662538/how-to-set-up-browsersync-to-correctly-serve-ajax-requests




写在最后: 约定优于配置——-软件开发的简约原则.


——————————– (完)————————————–


我的
个人网站:https://neveryu.github.io/guestbook/
Github: https://github.com/Neveryu
新浪微博:http://weibo.com/Neveryu


更多学习资源请关注我的新浪微博….

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读