【发布时间】:2014-11-08 15:39:48
【问题描述】:
如何通过 AngularJS 将 JSON 数据发布到网络服务 这是代码sn-p
.controller('MessagePostCtrl', function($scope, $http) {
$scope.postMessage = function() {
var msg = document.getElementById('message').value;
var msgdata = {
message : msg
};
var res = $http.post('http://<domain-name>/messenger/api/posts/savePost',msgdata);
res.success(function(data, status, headers, config) {
console.log(data);
});
}
})
选项 http:///messenger/api/posts/savePost
ionic.bundle.js:16185(匿名函数) ionic.bundle.js:16185 sendReq ionic.bundle.js:15979 serverRequest ionic.bundle.js:15712 包裹回调 ionic.bundle.js:19197 包裹回调 ionic.bundle.js:19197(匿名函数) ionic.bundle.js:19283 Scope.$eval ionic.bundle.js:20326 Scope.$digest ionic.bundle.js:20138 Scope.$apply ionic.bundle.js:20430(匿名函数) ionic.bundle.js:43025(匿名函数) ionic.bundle.js:10478 forEach ionic.bundle.js:7950 eventHandler ionic.bundle.js:10477 triggerMouseEvent ionic.bundle.js:2648 点击点击 ionic.bundle.js:2637 tapMouseUp ionic.bundle.js:2707XMLHttpRequest 无法加载 http:///messenger/api/posts/savePost。无效的 HTTP 状态码 404
但是当我从 $http.post 方法中删除 msgdata 时,一切正常。 谁能告诉我问题出在哪里,或者指导我如何将 JSON 数据发送到网络服务
感谢您的帮助
**Edited:
The Issue was with the CORS, Im using codeigniter REST Controller for web-services.
Modified the headers. If anyone has the same issue add the below header in the construct
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
Thanks to Linial for the break-through, telling me where the issue is.**
【问题讨论】:
-
您的网络服务需要 JSON 或表单数据吗? (例如:“message=test&x=test2”)
-
webservice 只需要 JSON 格式