有人能告诉我为什么下面的语句没有将post数据发送到指定的url吗?url被调用,但在服务器上,当我打印$_POST -我得到一个空数组。如果我在控制台中打印消息,然后将其添加到数据-它显示了正确的内容。
$http.post('request-url', { 'message' : message });
我也尝试过将数据作为字符串(具有相同的结果):
$http.post('request-url', "message=" + message);
当我以以下格式使用它时,它似乎正在工作:
$http({
method: 'POST',
url: 'request-url',
data: "message=" + message,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
但是是否有一种方法可以用$http.post() -我总是必须包括头以便它工作吗?我相信上面的内容类型是指定发送数据的格式,但我可以把它作为javascript对象发送吗?
我通过以下代码解决了这个问题:
客户端(Js):
$http({
url: me.serverPath,
method: 'POST',
data: data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
}).
success(function (serverData) {
console.log("ServerData:", serverData);
......
注意,data是一个对象。
在服务器端(ASP。NET MVC):
[AllowCrossSiteJson]
public string Api()
{
var data = JsonConvert.DeserializeObject<AgentRequest>(Request.Form[0]);
if (data == null) return "Null Request";
var bl = Page.Bl = new Core(this);
return data.methodName;
}
和'AllowCrossSiteJsonAttribute'需要跨域请求:
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
希望这对你有用。
你可以这样设置默认的“Content-Type”:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
关于数据格式:
美元的http。Post和$http。put方法接受任何JavaScript对象(或字符串)值作为其数据参数。如果data是一个JavaScript对象,默认情况下,它将被转换为JSON字符串。
试着使用这种变化
function sendData($scope) {
$http({
url: 'request-url',
method: "POST",
data: { 'message' : message }
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
}
只是提出一个现代化版本的@FelipeMiosso的答案:
.config(["$httpProvider", function ($httpProvider) {
function buildKey(parentKey, subKey) {
return parentKey + "[" + subKey + "]";
}
function buildObject(key, value) {
var object = {};
object[key] = value;
return object;
}
function join(array) {
return array.filter(function (entry) {
return entry;
}).join("&");
}
function arrayToQueryString(parentKey, array) {
return join(array.map(function (value, subKey) {
return toQueryString(buildObject(buildKey(parentKey, subKey), value));
}));
}
function objectToQueryString(parentKey, object) {
return join(Object.keys(object).map(function (subKey) {
return toQueryString(buildObject(buildKey(parentKey, subKey), object[subKey]));
}));
}
function toQueryString(input) {
return join(Object.keys(input).map(function (key) {
var value = input[key];
if (value instanceof Array) {
return arrayToQueryString(key, value);
} else if (value instanceof Object) {
return objectToQueryString(key, value);
} else if (undefined !== value && null !== value) {
return encodeURIComponent(key) + "=" + encodeURIComponent(value);
} else {
return "";
}
}));
}
function isQueryStringEligible(input) {
return null !== input && "object" === typeof input && "[object File]" !== String(input);
}
var interceptor = [function () {
return {
request: function (config) {
if (0 <= ["post", "put", "patch"].indexOf(config.method.toLowerCase()) && isQueryStringEligible(config.data)) {
config.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
config.data = toQueryString(config.data);
}
return config;
}
};
}];
$httpProvider.interceptors.push(interceptor);
}])
ES6版本:
.config(["$httpProvider", function ($httpProvider) {
"use strict";
const buildKey = (parentKey, subKey) => `${parentKey}[${subKey}]`;
const buildObject = (key, value) => ({ [key]: value });
const join = (array) => array.filter((entry) => entry).join("&");
const arrayToQueryString = (parentKey, array) =>
join(array.map((value, subKey) =>
toQueryString(buildObject(buildKey(parentKey, subKey), value))));
const objectToQueryString = (parentKey, object) =>
join(Object.keys(object).map((subKey) =>
toQueryString(buildObject(buildKey(parentKey, subKey), object[subKey]))));
const toQueryString = (input) => join(Object.keys(input).map((key) => {
const value = input[key];
if (value instanceof Array) {
return arrayToQueryString(key, value);
} else if (value instanceof Object) {
return objectToQueryString(key, value);
} else if (undefined !== value && null !== value) {
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
} else {
return "";
}
}));
const isQueryStringEligible = (input) =>
null !== input && "object" === typeof input && "[object File]" !== String(input);
const interceptor = [() => ({
request(config) {
if (0 <= ["post", "put", "patch"].indexOf(config.method.toLowerCase()) && isQueryStringEligible(config.data)) {
config.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
config.data = toQueryString(config.data);
}
return config;
}
})];
$httpProvider.interceptors.push(interceptor);
}])