Skip to content

Instantly share code, notes, and snippets.

@butchi
Created October 22, 2015 09:23
Show Gist options
  • Save butchi/517f356fd48d0906160c to your computer and use it in GitHub Desktop.
Save butchi/517f356fd48d0906160c to your computer and use it in GitHub Desktop.
jQueryのAjaxでJavaScriptファイルを取得するときの罠 ref: http://qiita.com/butchi_y/items/02f4ffd3b51055bcf536
httpData: function( r, type ) {
var ct = r.getResponseHeader("content-type");
var xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0;
var data = xml ? r.responseXML : r.responseText;
if ( xml && data.documentElement.tagName == "parsererror" )
throw "parsererror";
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
data = eval("(" + data + ")");
return data;
},
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Ajaxの罠</title>
</head>
<body>
<script src="jquery.js"></script>
<script src="main.js"></script>
</body>
</html>
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
$.ajax({
url: 'test.js',
dataType: 'text',
success: function(res) {
alert(res);
}
});
alert('hoge');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment