我正在尝试创建自己的 POST 请求。这是我的功能:
function sendPost(o) {
var h = new XMLHttpRequest();
h.onreadystatechange = requestComplete;
function requestComplete() {
if ( h.readyState === 4 ) {
if ( h.status === 200 ) {
if ( o.done ) {
o.done(h.responseText);
}
} else {
if ( o.fail ) {
o.fail(h.responseText);
}
}
}
}
h.open('POST', o.url, true);
h.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
h.send(o.data);
}
一切都很好,但我很困惑,如何将其 dataType 设置为 script,就像在 jQuery 中一样:
$.ajax({
url: 'someurl.php',
type: 'POST',
dataType: 'script' // <-- how to do this?
});
最佳答案
dataType
与发送 Ajax 请求关系不大。它主要是关于 jQuery 如何处理响应。
来自文档:
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
因此,在此处发送时需要进行一些修改。
- 拿
o.data
- 从
new Date()
获取时间戳 - 检查(通过查看
indexOf('?')
是否已有查询字符串 - 附加
?
或&
到 URL,后跟时间戳
剩下的就是处理响应:
Evaluates the response as JavaScript
所以:
eval(h.responseText);
<小时/>
尽管如此,这还是相当令人讨厌的。一般来说,如果您想动态加载脚本,通常最好添加 <script>
来实现。元素到页面。
关于javascript - 如何使用 dataType 作为脚本发送 AJAX?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18246611/