简体   繁体   English

为什么我的jQuery加载功能不起作用? -在Chrome上

[英]Why doesn't my jQuery load function work? - On Chrome

I have this html: 我有这个HTML:

<div class="box" id="n5">
    <p class="text">Lorem ipsum dolor sit amet</p>
    <textarea id="contentArea" rows="10" cols="50"></textarea>
    <div class="more">LikeAlink</div>
</div>

and this jQuery function: 和这个jQuery函数:

$(document).ready(function(){
    $(".box .more").click(function(event){
        $.ajax({
            url : "test.txt",
            success : function (data) {
                $("#contentArea").html(data);
            }
        });
    });
});

I found this solution on the Internet as an example. 我在Internet上找到了此解决方案作为示例。 Why does it not work for me? 为什么对我不起作用? I use Chrome, but the example worked on this browser. 我使用的是Chrome,但该示例在此浏览器上有效。

Content does not not appears in the text box. 内容未出现在文本框中。 Example

edit: 编辑:

I have this error message in the console: 我在控制台中收到以下错误消息:

XMLHttpRequest cannot load file:///C:/wamp/www/test.txt. XMLHttpRequest无法加载file:/// C:/wamp/www/test.txt。 Origin null is not allowed by Access-Control-Allow-Origin Access-Control-Allow-Origin不允许使用原点null

edit #2: 编辑#2:

for those interested, it seems to be a problem in Chrome on local servers. 对于那些感兴趣的人来说,在本地服务器上的Chrome中似乎是一个问题。 To test, start Chrome with this argument 要进行测试,请使用以下参数启动Chrome

--disable-web-security -禁用网络安全

chrome.exe --disable-web-security chrome.exe-禁用网络安全

As per your comment 根据您的评论

XMLHttpRequest cannot load file:///C:/wamp/www/text.txt. XMLHttpRequest无法加载file:/// C:/wamp/www/text.txt。 Origin null is not allowed by Access-Control-Allow-Origin Access-Control-Allow-Origin不允许使用原点null

This is because you're loading it from the file system instead of serving it through a web server. 这是因为您是从文件系统加载它,而不是通过Web服务器提供它。

I did that exact same thing with some JSON data and had the same results. 我对一些JSON数据执行了完全相同的操作,并得到了相同的结果。 Setup the correct MIME type in your web server and serve from http://example.com/text.txt instead of file:///C:/wamp/www/text.txt 在您的Web服务器中设置正确的MIME类型,并从http://example.com/text.txt而不是file:///C:/wamp/www/text.txt

If you think you have everything configured properly, try logging what the data returns as a first step. 如果您认为所有配置均正确,请尝试记录data返回的第一步。

$(document).ready(function(){
    $(".box .more").click(function(event){
        $.ajax({
            url : "test.txt",
            success : function (data) {
                // either
                alert(data);
                // or
                console.log(data);
            }
        });
    });
});

Read more on jquery.ajax over at the jQuery site. 在jQuery网站上阅读有关jquery.ajax的更多信息。

http://api.jquery.com/jQuery.ajax/ http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.ajaxSetup/ http://api.jquery.com/jQuery.ajaxSetup/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM