jQuery $.ajax(), $.post sending “OPTIONS” as REQUEST_METHOD in Firefox

前端 未结 23 2760
傲寒
傲寒 2020-11-22 14:38

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

The plugin should fetch data from a php script via ajax to add options to a

23条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 15:25

    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

    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.

提交回复
热议问题