Sending anything *other* than GET using JQuery ajax
I'm at the beginning of my ajax learning curve. I have a simple javascript function that uses jQuery.ajax()
to send data to the server and receive a simple text response. The function is correctly invoked on the server as expected and the response (which includes the value of request.method
as seen by the server) is returned and displayed via alert()
.
However, no matter what type:
I specify in my $.ajax() call
, the server always reports it has received a GET
.
Here is my javascript (again, I do see the alert()
, and it always reports GET
):
<script type="text/javascript">
function SendContactEntry() {
var payload = 'date=' + $('input[name=contact_date]').val() +
'&us=' + $('input[name=contact_us]').val() +
'&then=' + $('input[name=contact_them]').val() +
'¬e=' + encodeURIComponent($('input[name=contact_us]').val());
$.ajaxSetup({ jsonp: null, jsonpCallback: null});
$.ajax({type: 'POST',
url: '/contact',
data: payload,
cache: false,
contentType: 'application/json',
dataType: "text",
success: function (response){
alert(response);
}
开发者_Python百科}
);
}
</script>
and here is the CherryPy handler on the server:
class Contact:
def index(self):
return 'You sent a %s request' % cherrypy.request.method
I included the call to $.ajaxSetup() because of the answer to this question, but it doesn't seem to make a difference.
(jQuery and CherryPy are both latest versions, Python is 2.7)
EDITED: More Info.
Looking at my CherryPy console, I see that the server is receiving the POST. It's returning status 301 (moved) and then immediately it receives the same request as a GET and responds with status 200.
So it looks as if CherryPy is internally redirecting the POST to my handler as a GET. But why?
I'm afraid I'm going to have to answer my own question.
The problem is that CherryPy redirects /contact
to /contact/
if /contact
matches an internal index()
handler. The redirect is a GET
.
Changing
url: '/contact',
to
url: '/contact/',
solves the problem. I found the answer here.
To send a post request to the server try this open("POST","filename.extension",true);
精彩评论