So I'm trying to make a POST request using the jquery $.ajax
. My problem is the data being sent is JSON. So i'm not sure exactly how to send it. I am using fiddler to record the HTTP request and this is what I got. {"code":200,"user":"34522","questions":[{"35":"139"},{"55":"215"},{"28":"110"},{"88":"349"},{"127":"500"},{"148":"578"},{"125":"492"},{"218":"859"},{"258":"1019"},{"219":"862"}],"time":60}
. Under the webform of fiddler there is nothing there.
Here is the code I came up with and the response back is Object {code: 500, error: "Invalid request"}
var request = $.ajax({
url: "http://website/api/post/",
type: "POST",
data: {
code : 200,
user : 34522,
questions : '[{"35":"139"},{"55":"215"},{"28":"110"},{"88":"349"},{"127":"500"},{"148":"578"},{"125":"492"},{"218":"859"},{"258":"1019"},{"219":"862"}]',
time : 60
},
dataType: "json"
});
request.done(function( msg ) {
console.log(msg);
});
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
Try using JSON.stringify on your post data like this:
var request = $.ajax({
url: "http://website/api/post/",
type: "POST",
data: JSON.stringify({
code : 200,
user : 34522,
questions : [{"35":"139"},{"55":"215"},{"28":"110"},{"88":"349"},{"127":"500"},{"148":"578"},{"125":"492"},{"218":"859"},{"258":"1019"},{"219":"862"}],
time : 60
}),
dataType: "json"
});
JSON.stringify
will convert the current javascript object into a JSON string for posting. Also note removing the apostrophes from around the questions array.
The dataType:json refers to the response I believe. So if the server response isn't valid json, you would see a 500 error.
Try to look at the 'network (chrome)' or 'net (firefoxl)' tab in firebug to inspect the response.
You could also try to change dataType:json
to dataType:text
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.