Created
October 22, 2015 09:23
-
-
Save butchi/517f356fd48d0906160c to your computer and use it in GitHub Desktop.
jQueryのAjaxでJavaScriptファイルを取得するときの罠 ref: http://qiita.com/butchi_y/items/02f4ffd3b51055bcf536
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}, |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.ajax({ | |
url: 'test.js', | |
dataType: 'text', | |
success: function(res) { | |
alert(res); | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
alert('hoge'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment