I am making an ajax request using JQuery that looks like this:
var data = createXMLdata();
$.ajax({
url: 'http://localhost:8080/foo/bar',
type: "PUT",
data: data,
processData: false,
contentType: "application/text",
error: function(xhr, status, error) {
alert("Error: " + status);
},
success: function() {
alert("Success!");
}
});
When the code executes, I get the success alert, but the service is never executed on the server!
Here's some more data:
- If I make the same request using a separate REST client, the service is executed correctly
- If I shut down the server (nothing开发者_如何学运维 is running) so that hitting that URL gives me a 404, I still get a success message.
- I have tried replacing the data with "foo". This works from the REST client, but gives the same result from the code.
Any ideas are greatly appreciated!
The documentation about .ajax()
's type
attribute says:
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as
PUT
andDELETE
, can also be used here, but they are not supported by all browsers.
So probably your browser does not support PUT
and the data is sent via POST
instead (and therefore not recognized by your service).
Use Firebug or similar to find out which method is used.
One idea to make it working:
Send the data using POST
but add an additional field e.g. __http_method=PUT
. On the server side, your service has to recognize this and perform the PUT
functionality.
This might be not the nicest solution but it is also used by other frameworks I have encountered (e.g. symfony for PHP).
PUT isn't supported by all browsers
Nick Craver made a comment on my question:
Is the page you're running this in served from port 8080?
It turns out this led to me solving the problem. When both the app and the service were hosted on the same server (and port), the problem went away.
This post suggests that if I comment answers the question, and the commenter does not re-post as an answer, I am to post my own answer and accept it. Nick, if you return to post this as an answer, I will accept it over my own.
精彩评论