jQuery . ajax()美元。在Firefox中发送“选项”作为REQUEST_METHOD。

时间:2022-10-09 12:01:45

Having trouble with what I thought was a relatively simple jQuery plugin...

我认为jQuery插件相对简单,但遇到了问题……

The plugin should fetch data from a php script via ajax to add options to a <select>. The ajax request is pretty generic:

插件应该通过ajax从php脚本获取数据,以便向

$.ajax({
  url: o.url,
  type: 'post',
  contentType: "application/x-www-form-urlencoded",
  data: '{"method":"getStates", "program":"EXPLORE"}',
  success: function (data, status) {
    console.log("Success!!");
    console.log(data);
    console.log(status);
  },
  error: function (xhr, desc, err) {
    console.log(xhr);
    console.log("Desc: " + desc + "\nErr:" + err);
  }
});

This seems to work fine in Safari. In Firefox 3.5, the REQUEST_TYPE on the server is always 'OPTIONS', and the $_POST data does not appear. Apache logs the request as type 'OPTIONS':

这在Safari中似乎很有效。在Firefox 3.5中,服务器上的REQUEST_TYPE始终是“OPTIONS”,并且不会出现$_POST数据。Apache将请求记录为“选项”类型:

::1 - - [08/Jul/2009:11:43:27 -0500] "OPTIONS sitecodes.php HTTP/1.1" 200 46

Why would this ajax call work in Safari, but not Firefox, and how do I fix it for Firefox?

为什么这个ajax调用可以在Safari中工作,而不能在Firefox中工作?

Response Headers
Date: Wed, 08 Jul 2009 21:22:17 GMT
Server:Apache/2.0.59 (Unix) PHP/5.2.6 DAV/2
X-Powered-By: PHP/5.2.6
Content-Length  46
Keep-Alive  timeout=15, max=100
Connection  Keep-Alive
Content-Type    text/html

Request Headers
Host    orderform:8888
User-Agent  Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  300
Connection  keep-alive
Origin  http://ux.inetu.act.org
Access-Control-Request-Method   POST
Access-Control-Request-Headers  x-requested-with

Here is a picture of the Firebug output:

这是Firebug输出的图片:

jQuery . ajax()美元。在Firefox中发送“选项”作为REQUEST_METHOD。

23 个解决方案

#1


165  

The reason for the error is the same origin policy. It only allows you to do XMLHTTPRequests to your own domain. See if you can use a JSONP callback instead:

错误的原因是相同的起源策略。它只允许您对自己的域执行xmlhttprequest。看看是否可以使用JSONP回调:

$.getJSON( 'http://<url>/api.php?callback=?', function ( data ) { alert ( data ); } );

#2


55  

I used the following code on Django side to interpret the OPTIONS request and to set the required Access-Control headers. After this my cross domain requests from Firefox started working. As said before, the browser first sends the OPTIONS request and then immediately after that the POST/GET

我在Django上使用了以下代码来解释选项请求并设置所需的访问控制头。在此之后,Firefox的跨域请求开始工作。如前所述,浏览器首先发送选项请求,然后在POST/GET之后立即发送。

def send_data(request):
    if request.method == "OPTIONS": 
        response = HttpResponse()
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
        response['Access-Control-Max-Age'] = 1000
        # note that '*' is not valid for Access-Control-Allow-Headers
        response['Access-Control-Allow-Headers'] = 'origin, x-csrftoken, content-type, accept'
        return response
    if request.method == "POST":
        # ... 

Edit: it seems to be that at least in some cases you also need to add the same Access-Control headers to the actual response. This can be a little bit confusing, since the request seems to succeed, but Firefox does not pass the contents of the response to the Javascript.

编辑:似乎至少在某些情况下,您还需要向实际响应添加相同的访问控制头。这可能有点混乱,因为请求似乎成功了,但是Firefox没有将响应的内容传递给Javascript。

#3


16  

This mozilla developer center article describes various cross-domain request scenarios. The article seems to indicate that a POST request with content type of 'application/x-www-form-urlencoded' should be sent as a 'simple request' (with no 'preflight' OPTIONS request). I found , however, that Firefox sent the OPTIONS request, even though my POST was sent with that content type.

本文描述了各种跨域请求场景。这篇文章似乎表明,内容类型为“application/x-www-form- urlencodes”的POST请求应该作为“简单请求”(没有“飞行前”选项请求)发送。然而,我发现Firefox发送了选项请求,尽管我的文章是用该内容类型发送的。

I was able to make this work by creating an options request handler on the server, that set the 'Access-Control-Allow-Origin' response header to '*'. You can be more restrictive by setting it to something specific, like 'http://someurl.com'. Also, I have read that, supposedly, you can specify a comma-separated list of multiple origins, but I couldn't get this to work.

我可以通过在服务器上创建一个选项请求处理程序来完成这项工作,该处理程序将“访问控制允许的”响应头设置为“*”。你可以把它设置为特定的内容,比如“http://someurl.com”。另外,我读过,你可以指定一个逗号分隔的多起点的列表,但是我不能让它工作。

Once Firefox receives the response to the OPTIONS request with an acceptable 'Access-Control-Allow-Origin' value, it sends the POST request.

一旦Firefox接受了对选项请求的响应,并使用可接受的“访问控制允许源”值,它就会发送POST请求。

#4


15  

I've fixed this issue using an entirely-Apache based solution. In my vhost / htaccess I put the following block:

我已经使用一个完全基于apache的解决方案解决了这个问题。在我的vhost / htaccess中,我输入以下代码块:

# enable cross domain access control
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"

# force apache to return 200 without executing my scripts
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

You may not need the latter part, depending on what happens when Apache executes your target script. Credit goes to the friendly ServerFault folk for the latter part.

您可能不需要后面的部分,这取决于Apache执行目标脚本时会发生什么。后面的部分要归功于友好的服务器用户。

#5


10  

This PHP at the top of the responding script seems to work. (With Firefox 3.6.11. I have not yet done a lot of testing.)

在响应脚本顶部的这个PHP似乎起作用了。(Firefox 3.6.11。我还没有做过很多测试。

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
if(array_key_exists('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', $_SERVER)) {
    header('Access-Control-Allow-Headers: '
           . $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
} else {
    header('Access-Control-Allow-Headers: *');
}

if("OPTIONS" == $_SERVER['REQUEST_METHOD']) {
    exit(0);
}

#6


7  

I had same problem with sending requests to google maps, and solution is quite simple with jQuery 1.5 - for dataType use dataType: "jsonp"

我在向谷歌映射发送请求时遇到了同样的问题,jQuery 1.5的解决方案非常简单——对于数据类型,使用数据类型:“jsonp”

#7


4  

I was looking through source 1.3.2, when using JSONP, the request is made by building a SCRIPT element dynamically, which gets past the browsers Same-domain policy. Naturally, you can't make a POST request using a SCRIPT element, the browser would fetch the result using GET.

在使用JSONP时,我查看了源代码1.3.2,该请求是通过动态构建一个脚本元素来实现的,它通过了浏览器的同域策略。当然,不能使用脚本元素发出POST请求,浏览器将使用GET获取结果。

As you are requesting a JSONP call, the SCRIPT element is not generated, because it only does this when the Type of AJAX call is set to GET.

当您请求一个JSONP调用时,脚本元素并没有生成,因为只有在设置AJAX调用的类型时才会这样做。

http://dev.jquery.com/ticket/4690

http://dev.jquery.com/ticket/4690

#8


3  

We had a problem like this with ASP.Net. Our IIS was returning an Internal Server Error when trying to execute a jQuery $.post to get some html content due to PageHandlerFactory was restricted to respond only GET,HEAD,POST,DEBUG Verbs. So you can change that restriction adding the verb "OPTIONS" to the list or selecting "All Verbs"

我们在ASP.Net中遇到了这样的问题。我们的IIS在尝试执行jQuery $时返回了一个内部服务器错误。为了得到一些html内容,由于PageHandlerFactory被限制只响应get、HEAD、post、DEBUG谓词。所以你可以改变这个限制在列表中添加动词“选项”或者选择“所有动词”

You can modify that in your IIS Manager, selecting your website, then selecting Handler Mappings, double click in your PageHandlerFactory for *.apx files as you need (We use Integrated application pool with framework 4.0). Click on Request Restrictions, then go to Verbs Tabn and apply your modification.

您可以在IIS管理器中修改它,选择您的网站,然后选择处理程序映射,双击您的PageHandlerFactory for *。您需要的apx文件(我们使用框架4.0的集成应用程序池)。单击请求限制,然后转到谓词Tabn并应用您的修改。

Now our $.post request is working as expected :)

现在我们的美元。职位要求如预期的那样工作:)

#9


3  

Culprit is preflight request using OPTIONS method

罪魁祸首是使用OPTIONS方法的飞行前请求

For HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.

HTTP请求方法会导致用户数据上的副作用(尤其是对HTTP方法,除了得到,或与某些MIME类型)后使用,规范要求浏览器“起飞”请求,请求从服务器支持方法与HTTP请求方法选项,然后在“批准”从服务器,发送实际的请求与实际HTTP请求方法。

Web specification refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Web规范参考:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

I resolved the problem by adding following lines in Nginx conf.

我通过在Nginx conf中添加以下代码来解决这个问题。

    location / {
               if ($request_method = OPTIONS ) {
                   add_header Access-Control-Allow-Origin  "*";
                   add_header Access-Control-Allow-Methods "POST, GET, PUT, UPDATE, DELETE, OPTIONS";
                   add_header Access-Control-Allow-Headers "Authorization";
                   add_header Access-Control-Allow-Credentials  "true";
                   add_header Content-Length 0;
                   add_header Content-Type text/plain;
                   return 200;
               }
    location ~ ^/(xxxx)$ {
                if ($request_method = OPTIONS) {
                    rewrite ^(.*)$ / last;
                }
    }

#10


2  

Check if your form's action URL includes the www part of the domain, while the original page you have opened is viewed without www.

检查您的表单的操作URL是否包含域的www部分,而您打开的原始页面在没有www的情况下被查看。

Typically done for Canonical Urls..

通常用于规范url。

I struggled for hours before stumbling upon this article and found the hint of Cross Domain.

我花了好几个小时才偶然发现这篇文章,并发现了跨域的暗示。

#11


2  

I seems that if o.url = 'index.php' and this file exists is ok and returning a success message in the console. It returns an error if I use url:http://www.google.com

我觉得如果。url = '指数。php'和这个文件存在,并返回控制台中的成功消息。如果我使用url:http://www.google.com,它会返回一个错误。

If doing a post request why not using directly the $.post method:

如果做一个post请求为什么不直接使用$。post方法:

$.post("test.php", { func: "getNameAndTime" },
    function(data){
        alert(data.name); // John
        console.log(data.time); //  2pm
    }, "json");

It is so much simpler.

它简单得多。

#12


1  

I have posted a clear example of how to solve this if control the server code of the domain you are POSTing to. This answer is touched on in this thread, but this more clearly explains it IMO.

我已经发布了一个清晰的示例,说明如果控制要发布到的域的服务器代码,如何解决这个问题。这个答案在这条线索中有所涉及,但这在我看来更清楚地解释了它。

How do I send a cross-domain POST request via JavaScript?

如何通过JavaScript发送跨域POST请求?

#13


1  

Solution to this is:

解决方案是:

  1. use dataType: json
  2. 使用数据类型:json
  3. add &callback=? to your url
  4. 添加回调= ?你的网址

this worked on calling Facebook API and with Firefox. Firebug is using GET instead of OPTIONS with the above conditions (both of them).

它可以调用Facebook API和Firefox。Firebug使用的是GET而不是上述条件的选项(两者都是)。

#14


1  

Another possibility to circumvent the problem is to use a proxy script. That method is described for example here

绕过这个问题的另一种可能是使用代理脚本。例如,这里描述了该方法

#15


0  

Can you try this without

你能试一试吗?

contentType:application/x-www-form-urlencoded

contentType:应用程序/ x-www-form-urlencoded

#16


0  

Try adding the option:

尝试添加的选项:

dataType: "json"

数据类型:“json”

#17


0  

 function test_success(page,name,id,divname,str)
{ 
 var dropdownIndex = document.getElementById(name).selectedIndex;
 var dropdownValue = document.getElementById(name)[dropdownIndex].value;
 var params='&'+id+'='+dropdownValue+'&'+str;
 //makerequest_sp(url, params, divid1);

 $.ajax({
    url: page,
    type: "post",
    data: params,
    // callback handler that will be called on success
    success: function(response, textStatus, jqXHR){
        // log a message to the console
        document.getElementById(divname).innerHTML = response;

        var retname = 'n_district';
        var dropdownIndex = document.getElementById(retname).selectedIndex;
        var dropdownValue = document.getElementById(retname)[dropdownIndex].value;
        if(dropdownValue >0)
        {
            //alert(dropdownValue);
            document.getElementById('inputname').value = dropdownValue;
        }
        else
        {
            document.getElementById('inputname').value = "00";
        }
        return;
        url2=page2; 
        var params2 = parrams2+'&';
        makerequest_sp(url2, params2, divid2);

     }
});         
}

#18


0  

I had a similar problem with trying to use the Facebook API.

我在尝试使用Facebook API时遇到了类似的问题。

The only contentType which didn't send the Preflighted request seemed to be just text/plain... not the rest of the parameters mentioned at mozilla here

唯一没有发送预置请求的内容类型似乎只是文本/纯文本……这不是mozilla提到的其他参数。

  • Why is this the only browser which does this?
  • 为什么这是唯一的浏览器呢?
  • Why doesn't Facebook know and accept the preflight request?
  • 为什么Facebook不知道并接受预飞请求呢?

FYI: The aforementioned Moz doc suggests X-Lori headers should trigger a Preflighted request ... it doesn't.

前文提到的Moz博士建议X-Lori头部应该触发一个预置请求……它不是。

#19


0  

You need to do some work on server side. I see you are using PHP on server side, but solution for .NET web application is here: Cannot set content-type to 'application/json' in jQuery.ajax

您需要在服务器端做一些工作。我看到您在服务器端使用PHP,但是。net web应用程序的解决方案在这里:不能在jQuery.ajax中将内容类型设置为“application/json”

Do the same in PHP script and it will work. Simply: At first request browser is asking server if is allowed to send such data with such type and second request is the proper/allowed.

在PHP脚本中做同样的操作,它将会工作。简单地说:第一个请求浏览器询问服务器是否允许发送这种类型的数据,第二个请求是适当的/允许的。

#20


0  

Try to add the following:

尝试添加以下内容:

dataType: "json",
ContentType: "application/json",
data: JSON.stringify({"method":"getStates", "program":"EXPLORE"}),  

#21


0  

I used a proxy url to solve a similar problem when I want to post data to my apache solr hosted in another server. (This may not be the perfect answer but it solves my problem.)

当我想将数据发布到位于另一个服务器上的apache solr时,我使用了一个代理url来解决类似的问题。(这也许不是完美的答案,但它能解决我的问题。)

Follow this URL: Using Mode-Rewrite for proxying, I add this line to my httpd.conf:

遵循以下URL:使用代理的模式重写,我将这一行添加到我的httpd.conf:

 RewriteRule ^solr/(.*)$ http://ip:8983/solr$1 [P]

Therefore, I can just post data to /solr instead of posting data to http://ip:8983/solr/*. Then it will be posting data in the same origin.

因此,我可以将数据发布到/solr,而不是将数据发布到http://ip:8983/solr/*。然后,它将发布相同来源的数据。

#22


0  

I already have this code handling well my cors situation in php:

在php中,我已经有了很好地处理cors情况的代码:

header( 'Access-Control-Allow-Origin: '.CMSConfig::ALLOW_DOMAIN );
header( 'Access-Control-Allow-Headers: '.CMSConfig::ALLOW_DOMAIN );
header( 'Access-Control-Allow-Credentials: true' );

And it was working fine locally and remotely, but not for uploads when remote.

它在本地和远程上运行得很好,但在远程时不支持上传。

Something happen with apache/php OR my code, I didn't bother to search it, when you request OPTIONS it returns my header with cors rules but with 302 result. Therefore my browser doesn't recognise as an acceptable situation.

apache/php或我的代码发生了一些事情,我没有费心去搜索它,当你请求选项时,它返回带有cors规则的标题,但是返回302结果。因此,我的浏览器不能识别为可接受的情况。

What I did, based on @Mark McDonald answer, is just put this code after my header:

我所做的,基于@Mark McDonald的回答,就是把这段代码放在我的标题后面:

if( $_SERVER['REQUEST_METHOD'] === 'OPTIONS' )
{
    header("HTTP/1.1 202 Accepted");
    exit;
}

Now, when requesting OPTIONS it will just send the header and 202 result.

现在,当请求选项时,它将只发送header和202结果。

#23


-1  

Please be advised:

请注意:

JSONP supports only the GET request method.

JSONP只支持GET请求方法。

*Send request by firefox:*

*发送请求通过firefox:*

$.ajax({
   type: 'POST',//<<===
   contentType: 'application/json',
   url: url,
   dataType: "json"//<<=============
    ...
});

Above request send by OPTIONS(while ==>type: 'POST')!!!!

以上请求通过选项发送(而==>类型:'POST')!!!! !

$.ajax({
    type: 'POST',//<<===
    contentType: 'application/json',
    url: url,
    dataType: "jsonp"//<<==============
    ...
});

But above request send by GET(while ==>type: 'POST')!!!!

但以上请求通过GET发送(while =>类型:“POST”)!!!!

When you are in "cross-domain communication" , pay attention and be careful.

当你在“跨领域交流”时,要注意并小心。

#1


165  

The reason for the error is the same origin policy. It only allows you to do XMLHTTPRequests to your own domain. See if you can use a JSONP callback instead:

错误的原因是相同的起源策略。它只允许您对自己的域执行xmlhttprequest。看看是否可以使用JSONP回调:

$.getJSON( 'http://<url>/api.php?callback=?', function ( data ) { alert ( data ); } );

#2


55  

I used the following code on Django side to interpret the OPTIONS request and to set the required Access-Control headers. After this my cross domain requests from Firefox started working. As said before, the browser first sends the OPTIONS request and then immediately after that the POST/GET

我在Django上使用了以下代码来解释选项请求并设置所需的访问控制头。在此之后,Firefox的跨域请求开始工作。如前所述,浏览器首先发送选项请求,然后在POST/GET之后立即发送。

def send_data(request):
    if request.method == "OPTIONS": 
        response = HttpResponse()
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
        response['Access-Control-Max-Age'] = 1000
        # note that '*' is not valid for Access-Control-Allow-Headers
        response['Access-Control-Allow-Headers'] = 'origin, x-csrftoken, content-type, accept'
        return response
    if request.method == "POST":
        # ... 

Edit: it seems to be that at least in some cases you also need to add the same Access-Control headers to the actual response. This can be a little bit confusing, since the request seems to succeed, but Firefox does not pass the contents of the response to the Javascript.

编辑:似乎至少在某些情况下,您还需要向实际响应添加相同的访问控制头。这可能有点混乱,因为请求似乎成功了,但是Firefox没有将响应的内容传递给Javascript。

#3


16  

This mozilla developer center article describes various cross-domain request scenarios. The article seems to indicate that a POST request with content type of 'application/x-www-form-urlencoded' should be sent as a 'simple request' (with no 'preflight' OPTIONS request). I found , however, that Firefox sent the OPTIONS request, even though my POST was sent with that content type.

本文描述了各种跨域请求场景。这篇文章似乎表明,内容类型为“application/x-www-form- urlencodes”的POST请求应该作为“简单请求”(没有“飞行前”选项请求)发送。然而,我发现Firefox发送了选项请求,尽管我的文章是用该内容类型发送的。

I was able to make this work by creating an options request handler on the server, that set the 'Access-Control-Allow-Origin' response header to '*'. You can be more restrictive by setting it to something specific, like 'http://someurl.com'. Also, I have read that, supposedly, you can specify a comma-separated list of multiple origins, but I couldn't get this to work.

我可以通过在服务器上创建一个选项请求处理程序来完成这项工作,该处理程序将“访问控制允许的”响应头设置为“*”。你可以把它设置为特定的内容,比如“http://someurl.com”。另外,我读过,你可以指定一个逗号分隔的多起点的列表,但是我不能让它工作。

Once Firefox receives the response to the OPTIONS request with an acceptable 'Access-Control-Allow-Origin' value, it sends the POST request.

一旦Firefox接受了对选项请求的响应,并使用可接受的“访问控制允许源”值,它就会发送POST请求。

#4


15  

I've fixed this issue using an entirely-Apache based solution. In my vhost / htaccess I put the following block:

我已经使用一个完全基于apache的解决方案解决了这个问题。在我的vhost / htaccess中,我输入以下代码块:

# enable cross domain access control
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"

# force apache to return 200 without executing my scripts
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

You may not need the latter part, depending on what happens when Apache executes your target script. Credit goes to the friendly ServerFault folk for the latter part.

您可能不需要后面的部分,这取决于Apache执行目标脚本时会发生什么。后面的部分要归功于友好的服务器用户。

#5


10  

This PHP at the top of the responding script seems to work. (With Firefox 3.6.11. I have not yet done a lot of testing.)

在响应脚本顶部的这个PHP似乎起作用了。(Firefox 3.6.11。我还没有做过很多测试。

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
if(array_key_exists('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', $_SERVER)) {
    header('Access-Control-Allow-Headers: '
           . $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
} else {
    header('Access-Control-Allow-Headers: *');
}

if("OPTIONS" == $_SERVER['REQUEST_METHOD']) {
    exit(0);
}

#6


7  

I had same problem with sending requests to google maps, and solution is quite simple with jQuery 1.5 - for dataType use dataType: "jsonp"

我在向谷歌映射发送请求时遇到了同样的问题,jQuery 1.5的解决方案非常简单——对于数据类型,使用数据类型:“jsonp”

#7


4  

I was looking through source 1.3.2, when using JSONP, the request is made by building a SCRIPT element dynamically, which gets past the browsers Same-domain policy. Naturally, you can't make a POST request using a SCRIPT element, the browser would fetch the result using GET.

在使用JSONP时,我查看了源代码1.3.2,该请求是通过动态构建一个脚本元素来实现的,它通过了浏览器的同域策略。当然,不能使用脚本元素发出POST请求,浏览器将使用GET获取结果。

As you are requesting a JSONP call, the SCRIPT element is not generated, because it only does this when the Type of AJAX call is set to GET.

当您请求一个JSONP调用时,脚本元素并没有生成,因为只有在设置AJAX调用的类型时才会这样做。

http://dev.jquery.com/ticket/4690

http://dev.jquery.com/ticket/4690

#8


3  

We had a problem like this with ASP.Net. Our IIS was returning an Internal Server Error when trying to execute a jQuery $.post to get some html content due to PageHandlerFactory was restricted to respond only GET,HEAD,POST,DEBUG Verbs. So you can change that restriction adding the verb "OPTIONS" to the list or selecting "All Verbs"

我们在ASP.Net中遇到了这样的问题。我们的IIS在尝试执行jQuery $时返回了一个内部服务器错误。为了得到一些html内容,由于PageHandlerFactory被限制只响应get、HEAD、post、DEBUG谓词。所以你可以改变这个限制在列表中添加动词“选项”或者选择“所有动词”

You can modify that in your IIS Manager, selecting your website, then selecting Handler Mappings, double click in your PageHandlerFactory for *.apx files as you need (We use Integrated application pool with framework 4.0). Click on Request Restrictions, then go to Verbs Tabn and apply your modification.

您可以在IIS管理器中修改它,选择您的网站,然后选择处理程序映射,双击您的PageHandlerFactory for *。您需要的apx文件(我们使用框架4.0的集成应用程序池)。单击请求限制,然后转到谓词Tabn并应用您的修改。

Now our $.post request is working as expected :)

现在我们的美元。职位要求如预期的那样工作:)

#9


3  

Culprit is preflight request using OPTIONS method

罪魁祸首是使用OPTIONS方法的飞行前请求

For HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.

HTTP请求方法会导致用户数据上的副作用(尤其是对HTTP方法,除了得到,或与某些MIME类型)后使用,规范要求浏览器“起飞”请求,请求从服务器支持方法与HTTP请求方法选项,然后在“批准”从服务器,发送实际的请求与实际HTTP请求方法。

Web specification refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Web规范参考:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

I resolved the problem by adding following lines in Nginx conf.

我通过在Nginx conf中添加以下代码来解决这个问题。

    location / {
               if ($request_method = OPTIONS ) {
                   add_header Access-Control-Allow-Origin  "*";
                   add_header Access-Control-Allow-Methods "POST, GET, PUT, UPDATE, DELETE, OPTIONS";
                   add_header Access-Control-Allow-Headers "Authorization";
                   add_header Access-Control-Allow-Credentials  "true";
                   add_header Content-Length 0;
                   add_header Content-Type text/plain;
                   return 200;
               }
    location ~ ^/(xxxx)$ {
                if ($request_method = OPTIONS) {
                    rewrite ^(.*)$ / last;
                }
    }

#10


2  

Check if your form's action URL includes the www part of the domain, while the original page you have opened is viewed without www.

检查您的表单的操作URL是否包含域的www部分,而您打开的原始页面在没有www的情况下被查看。

Typically done for Canonical Urls..

通常用于规范url。

I struggled for hours before stumbling upon this article and found the hint of Cross Domain.

我花了好几个小时才偶然发现这篇文章,并发现了跨域的暗示。

#11


2  

I seems that if o.url = 'index.php' and this file exists is ok and returning a success message in the console. It returns an error if I use url:http://www.google.com

我觉得如果。url = '指数。php'和这个文件存在,并返回控制台中的成功消息。如果我使用url:http://www.google.com,它会返回一个错误。

If doing a post request why not using directly the $.post method:

如果做一个post请求为什么不直接使用$。post方法:

$.post("test.php", { func: "getNameAndTime" },
    function(data){
        alert(data.name); // John
        console.log(data.time); //  2pm
    }, "json");

It is so much simpler.

它简单得多。

#12


1  

I have posted a clear example of how to solve this if control the server code of the domain you are POSTing to. This answer is touched on in this thread, but this more clearly explains it IMO.

我已经发布了一个清晰的示例,说明如果控制要发布到的域的服务器代码,如何解决这个问题。这个答案在这条线索中有所涉及,但这在我看来更清楚地解释了它。

How do I send a cross-domain POST request via JavaScript?

如何通过JavaScript发送跨域POST请求?

#13


1  

Solution to this is:

解决方案是:

  1. use dataType: json
  2. 使用数据类型:json
  3. add &callback=? to your url
  4. 添加回调= ?你的网址

this worked on calling Facebook API and with Firefox. Firebug is using GET instead of OPTIONS with the above conditions (both of them).

它可以调用Facebook API和Firefox。Firebug使用的是GET而不是上述条件的选项(两者都是)。

#14


1  

Another possibility to circumvent the problem is to use a proxy script. That method is described for example here

绕过这个问题的另一种可能是使用代理脚本。例如,这里描述了该方法

#15


0  

Can you try this without

你能试一试吗?

contentType:application/x-www-form-urlencoded

contentType:应用程序/ x-www-form-urlencoded

#16


0  

Try adding the option:

尝试添加的选项:

dataType: "json"

数据类型:“json”

#17


0  

 function test_success(page,name,id,divname,str)
{ 
 var dropdownIndex = document.getElementById(name).selectedIndex;
 var dropdownValue = document.getElementById(name)[dropdownIndex].value;
 var params='&'+id+'='+dropdownValue+'&'+str;
 //makerequest_sp(url, params, divid1);

 $.ajax({
    url: page,
    type: "post",
    data: params,
    // callback handler that will be called on success
    success: function(response, textStatus, jqXHR){
        // log a message to the console
        document.getElementById(divname).innerHTML = response;

        var retname = 'n_district';
        var dropdownIndex = document.getElementById(retname).selectedIndex;
        var dropdownValue = document.getElementById(retname)[dropdownIndex].value;
        if(dropdownValue >0)
        {
            //alert(dropdownValue);
            document.getElementById('inputname').value = dropdownValue;
        }
        else
        {
            document.getElementById('inputname').value = "00";
        }
        return;
        url2=page2; 
        var params2 = parrams2+'&';
        makerequest_sp(url2, params2, divid2);

     }
});         
}

#18


0  

I had a similar problem with trying to use the Facebook API.

我在尝试使用Facebook API时遇到了类似的问题。

The only contentType which didn't send the Preflighted request seemed to be just text/plain... not the rest of the parameters mentioned at mozilla here

唯一没有发送预置请求的内容类型似乎只是文本/纯文本……这不是mozilla提到的其他参数。

  • Why is this the only browser which does this?
  • 为什么这是唯一的浏览器呢?
  • Why doesn't Facebook know and accept the preflight request?
  • 为什么Facebook不知道并接受预飞请求呢?

FYI: The aforementioned Moz doc suggests X-Lori headers should trigger a Preflighted request ... it doesn't.

前文提到的Moz博士建议X-Lori头部应该触发一个预置请求……它不是。

#19


0  

You need to do some work on server side. I see you are using PHP on server side, but solution for .NET web application is here: Cannot set content-type to 'application/json' in jQuery.ajax

您需要在服务器端做一些工作。我看到您在服务器端使用PHP,但是。net web应用程序的解决方案在这里:不能在jQuery.ajax中将内容类型设置为“application/json”

Do the same in PHP script and it will work. Simply: At first request browser is asking server if is allowed to send such data with such type and second request is the proper/allowed.

在PHP脚本中做同样的操作,它将会工作。简单地说:第一个请求浏览器询问服务器是否允许发送这种类型的数据,第二个请求是适当的/允许的。

#20


0  

Try to add the following:

尝试添加以下内容:

dataType: "json",
ContentType: "application/json",
data: JSON.stringify({"method":"getStates", "program":"EXPLORE"}),  

#21


0  

I used a proxy url to solve a similar problem when I want to post data to my apache solr hosted in another server. (This may not be the perfect answer but it solves my problem.)

当我想将数据发布到位于另一个服务器上的apache solr时,我使用了一个代理url来解决类似的问题。(这也许不是完美的答案,但它能解决我的问题。)

Follow this URL: Using Mode-Rewrite for proxying, I add this line to my httpd.conf:

遵循以下URL:使用代理的模式重写,我将这一行添加到我的httpd.conf:

 RewriteRule ^solr/(.*)$ http://ip:8983/solr$1 [P]

Therefore, I can just post data to /solr instead of posting data to http://ip:8983/solr/*. Then it will be posting data in the same origin.

因此,我可以将数据发布到/solr,而不是将数据发布到http://ip:8983/solr/*。然后,它将发布相同来源的数据。

#22


0  

I already have this code handling well my cors situation in php:

在php中,我已经有了很好地处理cors情况的代码:

header( 'Access-Control-Allow-Origin: '.CMSConfig::ALLOW_DOMAIN );
header( 'Access-Control-Allow-Headers: '.CMSConfig::ALLOW_DOMAIN );
header( 'Access-Control-Allow-Credentials: true' );

And it was working fine locally and remotely, but not for uploads when remote.

它在本地和远程上运行得很好,但在远程时不支持上传。

Something happen with apache/php OR my code, I didn't bother to search it, when you request OPTIONS it returns my header with cors rules but with 302 result. Therefore my browser doesn't recognise as an acceptable situation.

apache/php或我的代码发生了一些事情,我没有费心去搜索它,当你请求选项时,它返回带有cors规则的标题,但是返回302结果。因此,我的浏览器不能识别为可接受的情况。

What I did, based on @Mark McDonald answer, is just put this code after my header:

我所做的,基于@Mark McDonald的回答,就是把这段代码放在我的标题后面:

if( $_SERVER['REQUEST_METHOD'] === 'OPTIONS' )
{
    header("HTTP/1.1 202 Accepted");
    exit;
}

Now, when requesting OPTIONS it will just send the header and 202 result.

现在,当请求选项时,它将只发送header和202结果。

#23


-1  

Please be advised:

请注意:

JSONP supports only the GET request method.

JSONP只支持GET请求方法。

*Send request by firefox:*

*发送请求通过firefox:*

$.ajax({
   type: 'POST',//<<===
   contentType: 'application/json',
   url: url,
   dataType: "json"//<<=============
    ...
});

Above request send by OPTIONS(while ==>type: 'POST')!!!!

以上请求通过选项发送(而==>类型:'POST')!!!! !

$.ajax({
    type: 'POST',//<<===
    contentType: 'application/json',
    url: url,
    dataType: "jsonp"//<<==============
    ...
});

But above request send by GET(while ==>type: 'POST')!!!!

但以上请求通过GET发送(while =>类型:“POST”)!!!!

When you are in "cross-domain communication" , pay attention and be careful.

当你在“跨领域交流”时,要注意并小心。