简体   繁体   English

使用dataType脚本从jQuery.getScript或jQuery.ajax中检索脚本内容

[英]Retrieve script content from jQuery.getScript or jQuery.ajax with dataType script

According to jQuery's documentation, setting dataType: 'script' in $.ajax 根据jQuery的文档,在$.ajax设置dataType: 'script'

Evaluates the response as JavaScript and returns it as plain text. 将响应评估为JavaScript并以纯文本形式返回。

I got the evaluation part working fine but the response I get is undefined, not a plain text version of the javascript. 我的评估部分工作正常,但是得到的响应是不确定的,而不是纯文本版本的javascript。 I have tried this with $.ajax : 我已经尝试过$.ajax

$.ajax({
  url:url,
  dataType: 'script',
  success:function(data){
    //data is undefined but script runs as expected 
  }
});

I also tried using $.getScript with the same result: 我也尝试使用$.getScript获得相同的结果:

$.getScript(url, function(data){
    //data is null but script runs as expected 
});

jQuery will only return the body of the script if it's on the same domain the request originated from. jQuery仅在与请求源于同一域的情况下才返回脚本的主体。

You can see that it works by going to http://jquery.com and running this in your JS console: 您可以通过访问http://jquery.com并在JS控制台中运行它来查看它的工作原理:

$.getScript('/jquery-wp-content/themes/jquery/js/main.js', function(data){
  console.log(data);
});

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

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