javascript - 如何使用 dataType 作为脚本发送 AJAX?

标签 javascript ajax jquery

我正在尝试创建自己的 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.

因此,在此处发送时需要进行一些修改。

  1. o.data
  2. new Date() 获取时间戳
  3. 检查(通过查看 indexOf('?') 是否已有查询字符串
  4. 附加 ?&到 URL,后跟时间戳

剩下的就是处理响应:

Evaluates the response as JavaScript

所以:

eval(h.responseText);
<小时/>

尽管如此,这还是相当令人讨厌的。一般来说,如果您想动态加载脚本,通常最好添加 <script> 来实现。元素到页面。

关于javascript - 如何使用 dataType 作为脚本发送 AJAX?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18246611/

相关文章:

if 语句中的 JavaScript 错误 "Function expected"

php - Ajax 请求在 Meteor 中失败,但在 localhost 测试中正确

jquery - 使用特定宽度的视口(viewport)

jquery - Python-Django 如何在管理中使用 django-ajax-uploader?

jquery - 使用jQuery随机设置图像背景

javascript - 将ajax调用中返回的数据与JS函数中的数组值等同

javascript - 如何在 ExtJS 中将按钮放在表格的中心并让该表格填充容器?

javascript - Angular Flot - 通过 Alpha 传递十六进制颜色在 Google Chrome 中不起作用

javascript - 如何在步骤向导中继续对多个表单进行 ajax 调用

javascript - Ajax 在 Webix 中不起作用