【问题标题】:What is the difference between $.ajax with type: post and $.post$.ajax with type: post 和 $.post 有什么区别
【发布时间】:2013-10-06 04:34:17
【问题描述】:

考虑这段代码:

$.ajax({
           url: "http://x.com/api/AnnouncementCategory/Save",
           type: "Post",
           success: function (data) {
               //Grab our data from Ground Control
               alert(data);
           },
           error: function (event) {
               //If any errors occurred - detail them here
               alert("Transmission failed. (An error has occurred)");
           }
       });

使用上面的代码,我们可以跨域发布数据,一切正常。但是当我使用这段代码时:

$.post(' http://x.com/AnnouncementCategory/Save')

我收到此错误:

选项http://x.com/AnnouncementCategory/Save 请求 头字段 X-Requested-With 不允许 访问控制允许标头。 jquery-1.9.1.js:8526 XMLHttpRequest 无法加载 http://x.com/AnnouncementCategory/Save。要求 头字段 X-Requested-With 不允许 访问控制允许标头。

我看到jquery源代码:

function ( url, data, callback, type ) {
        // shift arguments if data argument was omitted
        if ( jQuery.isFunction( data ) ) {
            type = type || callback;
            callback = data;
            data = undefined;
        }

        return jQuery.ajax({
            url: url,
            type: method,
            dataType: type,
            data: data,
            success: callback
        });
    }

Jquery 在 post 中也使用 ajax。 **我知道我的错误是什么,只想知道:** $.ajax with type: post 和 jquery post 有什么区别?

【问题讨论】:

  • 可能什么都没有,但这是$.post 中的额外空间吗?就在http之前。

标签: javascript jquery ajax


【解决方案1】:

jQuery 的$.ajax 方法总是为任何跨域请求发送“x-requested-with”标头,这与$.post 不同。您得到的错误是由于外部服务器处理外部请求的方式。请look here 获取更多信息,了解如何处理 CORS(跨域资源共享 - 即跨域 Ajax)。也here你会发现类似的问题和解决方案。

【讨论】:

    【解决方案2】:

    您所问问题的简单答案是$.ajax 的简写版本,如文档中所述:

    http://api.jquery.com/jQuery.post/

    文档确实声明:

    由于浏览器安全限制,大多数“Ajax”请求都受制于 同源政策;请求无法成功检索 来自不同域、子域或协议的数据。

    你没有问的问题,但也许是你真正想问的问题,是 “为什么跨域请求对我使用带有简单 POST 类型的 $.ajax 有效,但不适用于$.post?”。为此,您可能需要提供更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 2015-09-14
      • 2017-03-15
      • 2015-08-03
      • 2011-03-11
      • 2011-10-11
      • 2011-03-05
      相关资源
      最近更新 更多