如何仅使用Dojo Toolkit重现此JQuery AJAX调用?
$.ajax({
url: "${pageContext.request.contextPath}/api/user/get",
data: JSON.stringify(requestParam),
type: "POST",
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(user)
{
}
});
我尝试使用此代码无效:
var xhrArgs =
{
url: "${pageContext.request.contextPath}/api/user/get",
postData: dojo.toJson(requestParam),
handleAs: "text",
load: function(user)
{
},
error: function(error)
{
}
}
var deferred = dojo.xhrPost(xhrArgs);
服务器返回:415 - The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().
如果重要的话,我在服务器端使用Spring MVC。
答案 0 :(得分:2)
如果您服务器的响应是JSON,那么Fikri是正确的,因为您需要将handleAs
设置为"json"
。但是,现在这不是你的主要问题。
在代码的jQuery版本中,您设置了2个标头。您似乎没有在代码的Dojo版本中设置它们。要设置标头,请在代码中添加headers
属性:
var xhrArgs =
{
url: "${pageContext.request.contextPath}/api/user/get",
postData: dojo.toJson(requestParam),
handleAs: "json",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
load: function(user)
{
},
error: function(error)
{
}
}
此外,如果您使用的是Dojo 1.8或更高版本,请改用新的dojo/request
API。
require(["dojo/request", "dojo/json"], function (request, JSON) {
var promise = request.post("${pageContext.request.contextPath}/api/user/get", {
data: JSON.stringify(requestParam),
handleAs: "json",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
}).then(function (user) {
// load callback
}, function (error) {
// error callback
});
});
答案 1 :(得分:0)
我的猜测是handleAs
键设置为text
。尝试将其更改为handleAs: 'json'